maven-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From mthmuld...@apache.org
Subject [maven] 03/04: Refactor MavenCli.populateRequest
Date Wed, 23 Sep 2020 11:59:22 GMT
This is an automated email from the ASF dual-hosted git repository.

mthmulders pushed a commit to branch mng-6118-submodule-invocation
in repository https://gitbox.apache.org/repos/asf/maven.git

commit 81234085ea8c16faccf8549bf8917177d2d68a9d
Author: Maarten Mulders <mthmulders@apache.org>
AuthorDate: Sat May 23 21:27:39 2020 +0200

    Refactor MavenCli.populateRequest
---
 .../execution/DefaultMavenExecutionRequest.java    |   6 +-
 .../main/java/org/apache/maven/cli/MavenCli.java   | 491 ++++++++++++---------
 .../java/org/apache/maven/cli/MavenCliTest.java    |  58 ++-
 3 files changed, 344 insertions(+), 211 deletions(-)

diff --git a/maven-core/src/main/java/org/apache/maven/execution/DefaultMavenExecutionRequest.java
b/maven-core/src/main/java/org/apache/maven/execution/DefaultMavenExecutionRequest.java
index fd00df9..f344359 100644
--- a/maven-core/src/main/java/org/apache/maven/execution/DefaultMavenExecutionRequest.java
+++ b/maven-core/src/main/java/org/apache/maven/execution/DefaultMavenExecutionRequest.java
@@ -64,9 +64,9 @@ public class DefaultMavenExecutionRequest
 
     private boolean interactiveMode = true;
 
-    private boolean cacheTransferError;
+    private boolean cacheTransferError = false;
 
-    private boolean cacheNotFound;
+    private boolean cacheNotFound = false;
 
     private List<Proxy> proxies;
 
@@ -159,7 +159,7 @@ public class DefaultMavenExecutionRequest
      *
      * @issue MNG-2681
      */
-    private boolean noSnapshotUpdates;
+    private boolean noSnapshotUpdates = false;
 
     private boolean useLegacyLocalRepositoryManager = false;
 
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 b0d6490..84a04c5 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
@@ -103,6 +103,7 @@ import java.io.InputStream;
 import java.io.PrintStream;
 import java.nio.file.Files;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Collections;
 import java.util.HashSet;
 import java.util.LinkedHashMap;
@@ -112,6 +113,7 @@ import java.util.Map.Entry;
 import java.util.Properties;
 import java.util.Set;
 import java.util.StringTokenizer;
+import java.util.function.Consumer;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
@@ -147,6 +149,8 @@ public class MavenCli
 
     public static final String STYLE_COLOR_PROPERTY = "style.color";
 
+    private static final String[] DEPRECATED_OPTIONS = { "up", "npu", "cpu", "npr" };
+
     private ClassWorld classWorld;
 
     private LoggerManager plexusLoggerManager;
@@ -1339,103 +1343,172 @@ public class MavenCli
         return populateRequest( cliRequest, cliRequest.request );
     }
 
-    @SuppressWarnings( "checkstyle:methodlength" )
     private MavenExecutionRequest populateRequest( CliRequest cliRequest, MavenExecutionRequest
request )
     {
+        slf4jLoggerFactory = LoggerFactory.getILoggerFactory();
         CommandLine commandLine = cliRequest.commandLine;
         String workingDirectory = cliRequest.workingDirectory;
         boolean quiet = cliRequest.quiet;
-        boolean showErrors = cliRequest.showErrors;
+        request.setShowErrors( cliRequest.showErrors ); // default: false
+        File baseDirectory = new File( workingDirectory, "" ).getAbsoluteFile();
 
-        String[] deprecatedOptions = { "up", "npu", "cpu", "npr" };
-        for ( String deprecatedOption : deprecatedOptions )
+        handleDeprecatedOptions( commandLine );
+
+        disableOnPresentOption( commandLine, CLIManager.BATCH_MODE, request::setInteractiveMode
);
+        enableOnPresentOption( commandLine, CLIManager.SUPRESS_SNAPSHOT_UPDATES, request::setNoSnapshotUpdates
);
+        request.setGoals( commandLine.getArgList() );
+        request.setReactorFailureBehavior( determineReactorFailureBehaviour ( commandLine
) );
+        disableOnPresentOption( commandLine, CLIManager.NON_RECURSIVE, request::setRecursive
);
+        enableOnPresentOption( commandLine, CLIManager.OFFLINE, request::setOffline );
+        enableOnPresentOption( commandLine, CLIManager.UPDATE_SNAPSHOTS, request::setUpdateSnapshots
);
+        request.setGlobalChecksumPolicy( determineGlobalCheckPolicy( commandLine ) );
+        request.setBaseDirectory( baseDirectory );
+        request.setSystemProperties( cliRequest.systemProperties );
+        request.setUserProperties( cliRequest.userProperties );
+        request.setMultiModuleProjectDirectory( cliRequest.multiModuleProjectDirectory );
+        request.setPom( determinePom( commandLine, workingDirectory, baseDirectory ) );
+        request.setTransferListener( determineTransferListener( quiet, commandLine, request
) );
+        request.setExecutionListener( determineExecutionListener() );
+
+        if ( ( request.getPom() != null ) && ( request.getPom().getParentFile() !=
null ) )
         {
-            if ( commandLine.hasOption( deprecatedOption ) )
-            {
-                slf4jLogger.warn( "Command line option -{} is deprecated and will be removed
in future Maven versions.",
-                        deprecatedOption );
-            }
+            request.setBaseDirectory( request.getPom().getParentFile() );
         }
 
-        // ----------------------------------------------------------------------
-        // Now that we have everything that we need we will fire up plexus and
-        // bring the maven component to life for use.
-        // ----------------------------------------------------------------------
+        request.setResumeFrom( commandLine.getOptionValue( CLIManager.RESUME_FROM ) );
+        enableOnPresentOption( commandLine, CLIManager.RESUME, request::setResume );
+        request.setMakeBehavior( determineMakeBehavior( commandLine ) );
+        request.setCacheNotFound( true );
+        request.setCacheTransferError( false );
 
-        if ( commandLine.hasOption( CLIManager.BATCH_MODE ) )
-        {
-            request.setInteractiveMode( false );
-        }
+        final ProjectActivation projectActivation = determineProjectActivation( commandLine
);
+        request.setSelectedProjects( projectActivation.activeProjects );
+        request.setExcludedProjects( projectActivation.inactiveProjects );
 
-        boolean noSnapshotUpdates = false;
-        if ( commandLine.hasOption( CLIManager.SUPRESS_SNAPSHOT_UPDATES ) )
-        {
-            noSnapshotUpdates = true;
-        }
+        final ProfileActivation profileActivation = determineProfileActivation( commandLine
);
+        request.addActiveProfiles( profileActivation.activeProfiles );
+        request.addInactiveProfiles( profileActivation.inactiveProfiles );
+
+        request.setLocalRepositoryPath( determineLocalRepositoryPath( request ) );
 
-        // ----------------------------------------------------------------------
         //
-        // ----------------------------------------------------------------------
+        // Builder, concurrency and parallelism
+        //
+        // We preserve the existing methods for builder selection which is to look for various
inputs in the threading
+        // configuration. We don't have an easy way to allow a pluggable builder to provide
its own configuration
+        // parameters but this is sufficient for now. Ultimately we want components like
Builders to provide a way to
+        // extend the command line to accept its own configuration parameters.
+        //
+        final String threadConfiguration = commandLine.getOptionValue( CLIManager.THREADS
);
 
-        List<String> goals = commandLine.getArgList();
+        if ( threadConfiguration != null )
+        {
+            //
+            // Default to the standard multithreaded builder
+            //
+            request.setBuilderId( "multithreaded" );
 
-        boolean recursive = true;
+            if ( threadConfiguration.contains( "C" ) )
+            {
+                request.setDegreeOfConcurrency( calculateDegreeOfConcurrencyWithCoreMultiplier(
threadConfiguration ) );
+            }
+            else
+            {
+                request.setDegreeOfConcurrency( Integer.parseInt( threadConfiguration ) );
+            }
+        }
 
-        // this is the default behavior.
-        String reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST;
+        //
+        // Allow the builder to be overridden by the user if requested. The builders are
now pluggable.
+        //
+        request.setBuilderId( commandLine.getOptionValue( CLIManager.BUILDER, request.getBuilderId()
) );
 
-        slf4jLoggerFactory = LoggerFactory.getILoggerFactory();
+        return request;
+    }
 
-        if ( commandLine.hasOption( CLIManager.NON_RECURSIVE ) )
-        {
-            recursive = false;
-        }
+    private String determineLocalRepositoryPath( final MavenExecutionRequest request )
+    {
+        return request.getUserProperties().getProperty(
+                MavenCli.LOCAL_REPO_PROPERTY,
+                request.getSystemProperties().getProperty( MavenCli.LOCAL_REPO_PROPERTY )
// null if not found
+        );
+    }
 
-        if ( commandLine.hasOption( CLIManager.FAIL_FAST ) )
+    private File determinePom( final CommandLine commandLine, final String workingDirectory,
final File baseDirectory )
+    {
+        String alternatePomFile = null;
+        if ( commandLine.hasOption( CLIManager.ALTERNATE_POM_FILE ) )
         {
-            reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST;
+            alternatePomFile = commandLine.getOptionValue( CLIManager.ALTERNATE_POM_FILE
);
         }
-        else if ( commandLine.hasOption( CLIManager.FAIL_AT_END ) )
+
+        if ( alternatePomFile != null )
         {
-            reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_AT_END;
+            File pom = resolveFile( new File( alternatePomFile ), workingDirectory );
+            if ( pom.isDirectory() )
+            {
+                pom = new File( pom, "pom.xml" );
+            }
+
+            return pom;
         }
-        else if ( commandLine.hasOption( CLIManager.FAIL_NEVER ) )
+        else if ( modelProcessor != null )
         {
-            reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_NEVER;
-        }
+            File pom = modelProcessor.locatePom( baseDirectory );
 
-        if ( commandLine.hasOption( CLIManager.OFFLINE ) )
-        {
-            request.setOffline( true );
+            if ( pom.isFile() )
+            {
+                return pom;
+            }
         }
 
-        boolean updateSnapshots = false;
+        return null;
+    }
+
+    // Visible for testing
+    static ProjectActivation determineProjectActivation ( final CommandLine commandLine )
+    {
+        final ProjectActivation projectActivation = new ProjectActivation();
 
-        if ( commandLine.hasOption( CLIManager.UPDATE_SNAPSHOTS ) )
+        if ( commandLine.hasOption( CLIManager.PROJECT_LIST ) )
         {
-            updateSnapshots = true;
-        }
+            String[] projectOptionValues = commandLine.getOptionValues( CLIManager.PROJECT_LIST
);
 
-        String globalChecksumPolicy = null;
+            if ( projectOptionValues != null )
+            {
+                for ( String projectOptionValue : projectOptionValues )
+                {
+                    StringTokenizer projectTokens = new StringTokenizer( projectOptionValue,
"," );
 
-        if ( commandLine.hasOption( CLIManager.CHECKSUM_FAILURE_POLICY ) )
-        {
-            globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_FAIL;
-        }
-        else if ( commandLine.hasOption( CLIManager.CHECKSUM_WARNING_POLICY ) )
-        {
-            globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_WARN;
-        }
+                    while ( projectTokens.hasMoreTokens() )
+                    {
+                        String projectAction = projectTokens.nextToken().trim();
 
-        File baseDirectory = new File( workingDirectory, "" ).getAbsoluteFile();
+                        if ( projectAction.startsWith( "-" ) || projectAction.startsWith(
"!" ) )
+                        {
+                            projectActivation.deactivate( projectAction.substring( 1 ) );
+                        }
+                        else if ( projectAction.startsWith( "+" ) )
+                        {
+                            projectActivation.activate( projectAction.substring( 1 ) );
+                        }
+                        else
+                        {
+                            projectActivation.activate( projectAction );
+                        }
+                    }
+                }
+            }
 
-        // ----------------------------------------------------------------------
-        // Profile Activation
-        // ----------------------------------------------------------------------
+        }
 
-        List<String> activeProfiles = new ArrayList<>();
+        return projectActivation;
+    }
 
-        List<String> inactiveProfiles = new ArrayList<>();
+    // Visible for testing
+    static ProfileActivation determineProfileActivation( final CommandLine commandLine )
+    {
+        final ProfileActivation result = new ProfileActivation();
 
         if ( commandLine.hasOption( CLIManager.ACTIVATE_PROFILES ) )
         {
@@ -1452,207 +1525,169 @@ public class MavenCli
 
                         if ( profileAction.startsWith( "-" ) || profileAction.startsWith(
"!" ) )
                         {
-                            inactiveProfiles.add( profileAction.substring( 1 ) );
+                            result.deactivate( profileAction.substring( 1 ) );
                         }
                         else if ( profileAction.startsWith( "+" ) )
                         {
-                            activeProfiles.add( profileAction.substring( 1 ) );
+                            result.activate( profileAction.substring( 1 ) );
                         }
                         else
                         {
-                            activeProfiles.add( profileAction );
+                            result.activate( profileAction );
                         }
                     }
                 }
             }
         }
 
-        TransferListener transferListener;
+        return result;
+    }
 
-        if ( quiet || cliRequest.commandLine.hasOption( CLIManager.NO_TRANSFER_PROGRESS )
)
+    private ExecutionListener determineExecutionListener()
+    {
+        ExecutionListener executionListener = new ExecutionEventLogger();
+        if ( eventSpyDispatcher != null )
         {
-            transferListener = new QuietMavenTransferListener();
-        }
-        else if ( request.isInteractiveMode() && !cliRequest.commandLine.hasOption(
CLIManager.LOG_FILE ) )
-        {
-            //
-            // If we're logging to a file then we don't want the console transfer listener
as it will spew
-            // download progress all over the place
-            //
-            transferListener = getConsoleTransferListener( cliRequest.commandLine.hasOption(
CLIManager.DEBUG ) );
+            return eventSpyDispatcher.chainListener( executionListener );
         }
         else
         {
-            transferListener = getBatchTransferListener();
+            return executionListener;
         }
+    }
 
-        ExecutionListener executionListener = new ExecutionEventLogger();
-        if ( eventSpyDispatcher != null )
+    private void handleDeprecatedOptions( final CommandLine commandLine )
+    {
+        Arrays.stream( DEPRECATED_OPTIONS )
+                .filter( commandLine::hasOption )
+                .forEach( deprecatedOption -> slf4jLogger.warn(
+                        "Command line option -{} is deprecated and will be removed in future
Maven versions.",
+                        deprecatedOption )
+                );
+    }
+
+    private String determineReactorFailureBehaviour( final CommandLine commandLine )
+    {
+        if ( commandLine.hasOption( CLIManager.FAIL_FAST ) )
         {
-            executionListener = eventSpyDispatcher.chainListener( executionListener );
+            return MavenExecutionRequest.REACTOR_FAIL_FAST;
         }
-
-        String alternatePomFile = null;
-        if ( commandLine.hasOption( CLIManager.ALTERNATE_POM_FILE ) )
+        else if ( commandLine.hasOption( CLIManager.FAIL_AT_END ) )
         {
-            alternatePomFile = commandLine.getOptionValue( CLIManager.ALTERNATE_POM_FILE
);
+            return MavenExecutionRequest.REACTOR_FAIL_AT_END;
         }
-
-        request.setBaseDirectory( baseDirectory ).setGoals( goals ).setSystemProperties(
-            cliRequest.systemProperties ).setUserProperties( cliRequest.userProperties ).setReactorFailureBehavior(
-            reactorFailureBehaviour ) // default: fail fast
-            .setRecursive( recursive ) // default: true
-            .setShowErrors( showErrors ) // default: false
-            .addActiveProfiles( activeProfiles ) // optional
-            .addInactiveProfiles( inactiveProfiles ) // optional
-            .setExecutionListener( executionListener ).setTransferListener(
-            transferListener ) // default: batch mode which goes along with interactive
-            .setUpdateSnapshots( updateSnapshots ) // default: false
-            .setNoSnapshotUpdates( noSnapshotUpdates ) // default: false
-            .setGlobalChecksumPolicy( globalChecksumPolicy ) // default: warn
-            .setMultiModuleProjectDirectory( cliRequest.multiModuleProjectDirectory );
-
-        if ( alternatePomFile != null )
+        else if ( commandLine.hasOption( CLIManager.FAIL_NEVER ) )
         {
-            File pom = resolveFile( new File( alternatePomFile ), workingDirectory );
-            if ( pom.isDirectory() )
-            {
-                pom = new File( pom, "pom.xml" );
-            }
-
-            request.setPom( pom );
+            return MavenExecutionRequest.REACTOR_FAIL_NEVER;
         }
-        else if ( modelProcessor != null )
+        else
         {
-            File pom = modelProcessor.locatePom( baseDirectory );
-
-            if ( pom.isFile() )
-            {
-                request.setPom( pom );
-            }
+            // this is the default behavior.
+            return MavenExecutionRequest.REACTOR_FAIL_FAST;
         }
+    }
 
-        if ( ( request.getPom() != null ) && ( request.getPom().getParentFile() !=
null ) )
+    private TransferListener determineTransferListener( final boolean quiet,
+                                                        final CommandLine commandLine,
+                                                        final MavenExecutionRequest request
)
+    {
+        if ( quiet || commandLine.hasOption( CLIManager.NO_TRANSFER_PROGRESS ) )
         {
-            request.setBaseDirectory( request.getPom().getParentFile() );
+            return new QuietMavenTransferListener();
         }
-
-        if ( commandLine.hasOption( CLIManager.RESUME ) )
+        else if ( request.isInteractiveMode() && !commandLine.hasOption( CLIManager.LOG_FILE
) )
         {
-            request.setResume( true );
+            //
+            // If we're logging to a file then we don't want the console transfer listener
as it will spew
+            // download progress all over the place
+            //
+            return getConsoleTransferListener( commandLine.hasOption( CLIManager.DEBUG )
);
         }
-
-        if ( commandLine.hasOption( CLIManager.RESUME_FROM ) )
+        else
         {
-            request.setResumeFrom( commandLine.getOptionValue( CLIManager.RESUME_FROM ) );
+            // default: batch mode which goes along with interactive
+            return getBatchTransferListener();
         }
+    }
 
-        if ( commandLine.hasOption( CLIManager.PROJECT_LIST ) )
+    private String determineMakeBehavior( final CommandLine cl )
+    {
+        if ( cl.hasOption( CLIManager.ALSO_MAKE ) && !cl.hasOption( CLIManager.ALSO_MAKE_DEPENDENTS
) )
         {
-            String[] projectOptionValues = commandLine.getOptionValues( CLIManager.PROJECT_LIST
);
-
-            List<String> inclProjects = new ArrayList<>();
-            List<String> exclProjects = new ArrayList<>();
-
-            if ( projectOptionValues != null )
-            {
-                for ( String projectOptionValue : projectOptionValues )
-                {
-                    StringTokenizer projectTokens = new StringTokenizer( projectOptionValue,
"," );
-
-                    while ( projectTokens.hasMoreTokens() )
-                    {
-                        String projectAction = projectTokens.nextToken().trim();
-
-                        if ( projectAction.startsWith( "-" ) || projectAction.startsWith(
"!" ) )
-                        {
-                            exclProjects.add( projectAction.substring( 1 ) );
-                        }
-                        else if ( projectAction.startsWith( "+" ) )
-                        {
-                            inclProjects.add( projectAction.substring( 1 ) );
-                        }
-                        else
-                        {
-                            inclProjects.add( projectAction );
-                        }
-                    }
-                }
-            }
-
-            request.setSelectedProjects( inclProjects );
-            request.setExcludedProjects( exclProjects );
+            return MavenExecutionRequest.REACTOR_MAKE_UPSTREAM;
         }
-
-        if ( commandLine.hasOption( CLIManager.ALSO_MAKE ) && !commandLine.hasOption(
-            CLIManager.ALSO_MAKE_DEPENDENTS ) )
+        else if ( !cl.hasOption( CLIManager.ALSO_MAKE ) && cl.hasOption( CLIManager.ALSO_MAKE_DEPENDENTS
) )
         {
-            request.setMakeBehavior( MavenExecutionRequest.REACTOR_MAKE_UPSTREAM );
+            return MavenExecutionRequest.REACTOR_MAKE_DOWNSTREAM;
         }
-        else if ( !commandLine.hasOption( CLIManager.ALSO_MAKE ) && commandLine.hasOption(
-            CLIManager.ALSO_MAKE_DEPENDENTS ) )
+        else if ( cl.hasOption( CLIManager.ALSO_MAKE ) && cl.hasOption( CLIManager.ALSO_MAKE_DEPENDENTS
) )
         {
-            request.setMakeBehavior( MavenExecutionRequest.REACTOR_MAKE_DOWNSTREAM );
+            return MavenExecutionRequest.REACTOR_MAKE_BOTH;
         }
-        else if ( commandLine.hasOption( CLIManager.ALSO_MAKE ) && commandLine.hasOption(
-            CLIManager.ALSO_MAKE_DEPENDENTS ) )
+        else
         {
-            request.setMakeBehavior( MavenExecutionRequest.REACTOR_MAKE_BOTH );
+            return null;
         }
+    }
 
-        String localRepoProperty = request.getUserProperties().getProperty( MavenCli.LOCAL_REPO_PROPERTY
);
-
-        if ( localRepoProperty == null )
+    private String determineGlobalCheckPolicy( final CommandLine commandLine )
+    {
+        if ( commandLine.hasOption( CLIManager.CHECKSUM_FAILURE_POLICY ) )
         {
-            localRepoProperty = request.getSystemProperties().getProperty( MavenCli.LOCAL_REPO_PROPERTY
);
+            return MavenExecutionRequest.CHECKSUM_POLICY_FAIL;
         }
-
-        if ( localRepoProperty != null )
+        else if ( commandLine.hasOption( CLIManager.CHECKSUM_WARNING_POLICY ) )
         {
-            request.setLocalRepositoryPath( localRepoProperty );
+            return MavenExecutionRequest.CHECKSUM_POLICY_WARN;
         }
+        else
+        {
+            return null;
+        }
+    }
 
-        request.setCacheNotFound( true );
-        request.setCacheTransferError( false );
+    private void disableOnPresentOption( final CommandLine commandLine,
+                                         final String option,
+                                         final Consumer<Boolean> setting )
+    {
+        if ( commandLine.hasOption( option ) )
+        {
+            setting.accept( false );
+        }
+    }
 
-        //
-        // Builder, concurrency and parallelism
-        //
-        // We preserve the existing methods for builder selection which is to look for various
inputs in the threading
-        // configuration. We don't have an easy way to allow a pluggable builder to provide
its own configuration
-        // parameters but this is sufficient for now. Ultimately we want components like
Builders to provide a way to
-        // extend the command line to accept its own configuration parameters.
-        //
-        final String threadConfiguration = commandLine.hasOption( CLIManager.THREADS )
-            ? commandLine.getOptionValue( CLIManager.THREADS )
-            : null;
+    private void disableOnPresentOption( final CommandLine commandLine,
+                                         final char option,
+                                         final Consumer<Boolean> setting )
+    {
+        disableOnPresentOption( commandLine, String.valueOf( option ), setting );
+    }
 
-        if ( threadConfiguration != null )
+    private void enableOnPresentOption( final CommandLine commandLine,
+                                        final String option,
+                                        final Consumer<Boolean> setting )
+    {
+        if ( commandLine.hasOption( option ) )
         {
-            //
-            // Default to the standard multithreaded builder
-            //
-            request.setBuilderId( "multithreaded" );
-
-            if ( threadConfiguration.contains( "C" ) )
-            {
-                request.setDegreeOfConcurrency( calculateDegreeOfConcurrencyWithCoreMultiplier(
threadConfiguration ) );
-            }
-            else
-            {
-                request.setDegreeOfConcurrency( Integer.parseInt( threadConfiguration ) );
-            }
+            setting.accept( true );
         }
+    }
 
-        //
-        // Allow the builder to be overridden by the user if requested. The builders are
now pluggable.
-        //
-        if ( commandLine.hasOption( CLIManager.BUILDER ) )
+    private void enableOnPresentOption( final CommandLine commandLine,
+                                        final char option,
+                                        final Consumer<Boolean> setting )
+    {
+        enableOnPresentOption( commandLine, String.valueOf( option ), setting );
+    }
+
+    private void enableOnAbsentOption( final CommandLine commandLine,
+                                       final char option,
+                                       final Consumer<Boolean> setting )
+    {
+        if ( !commandLine.hasOption( option ) )
         {
-            request.setBuilderId( commandLine.getOptionValue( CLIManager.BUILDER ) );
+            setting.accept( true );
         }
-
-        return request;
     }
 
     int calculateDegreeOfConcurrencyWithCoreMultiplier( String threadConfiguration )
@@ -1769,4 +1804,46 @@ public class MavenCli
     {
         return container.lookup( ModelProcessor.class );
     }
+
+    // Visible for testing
+    static class ProfileActivation
+    {
+        final List<String> activeProfiles = new ArrayList<>();
+        final List<String> inactiveProfiles = new ArrayList<>();
+
+        public void deactivate( final String profile )
+        {
+            inactiveProfiles.add( profile );
+        }
+
+        public void activate( final String profile )
+        {
+            activeProfiles.add( profile );
+        }
+    }
+
+    // Visible for testing
+    static class ProjectActivation
+    {
+        List<String> activeProjects;
+        List<String> inactiveProjects;
+
+        public void deactivate( final String project )
+        {
+            if ( inactiveProjects == null )
+            {
+                inactiveProjects = new ArrayList<>();
+            }
+            inactiveProjects.add( project );
+        }
+
+        public void activate( final String project )
+        {
+            if ( activeProjects == null )
+            {
+                activeProjects = new ArrayList<>();
+            }
+            activeProjects.add( project );
+        }
+    }
 }
diff --git a/maven-embedder/src/test/java/org/apache/maven/cli/MavenCliTest.java b/maven-embedder/src/test/java/org/apache/maven/cli/MavenCliTest.java
index b0e536f..8c87527 100644
--- a/maven-embedder/src/test/java/org/apache/maven/cli/MavenCliTest.java
+++ b/maven-embedder/src/test/java/org/apache/maven/cli/MavenCliTest.java
@@ -20,14 +20,18 @@ package org.apache.maven.cli;
  */
 
 import static java.util.Arrays.asList;
+import static org.apache.maven.cli.MavenCli.determineProfileActivation;
+import static org.apache.maven.cli.MavenCli.determineProjectActivation;
 import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.is;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 import static org.junit.Assume.assumeTrue;
 import static org.mockito.ArgumentMatchers.any;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
 import static org.mockito.Mockito.inOrder;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.times;
@@ -36,6 +40,10 @@ import java.io.File;
 import java.util.Collections;
 import java.util.List;
 
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.GnuParser;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
 import org.apache.commons.cli.ParseException;
 import org.apache.maven.Maven;
 import org.apache.maven.eventspy.internal.EventSpyDispatcher;
@@ -82,6 +90,54 @@ public class MavenCliTest
     }
 
     @Test
+    public void testDetermineProfileActivation() throws ParseException
+    {
+        MavenCli.ProfileActivation result;
+        Options options = new Options();
+        options.addOption( Option.builder( Character.toString( CLIManager.ACTIVATE_PROFILES
) ).hasArg().build() );
+
+        result = determineProfileActivation( new GnuParser().parse( options, new String[]{
"-P", "test1,+test2" } ) );
+        assertThat( result.activeProfiles.size(), is( 2 ) );
+        assertThat( result.activeProfiles, contains( "test1", "test2" ) );
+
+        result = determineProfileActivation( new GnuParser().parse( options, new String[]{
"-P", "!test1,-test2" } ) );
+        assertThat( result.inactiveProfiles.size(), is( 2 ) );
+        assertThat( result.inactiveProfiles, contains( "test1", "test2" ) );
+
+        result = determineProfileActivation( new GnuParser().parse( options, new String[]{
"-P", "-test1,+test2" } ) );
+        assertThat( result.activeProfiles.size(), is( 1 ) );
+        assertThat( result.activeProfiles, contains( "test2" ) );
+        assertThat( result.inactiveProfiles.size(), is( 1 ) );
+        assertThat( result.inactiveProfiles, contains( "test1" ) );
+    }
+
+    @Test
+    public void testDetermineProjectActivation() throws ParseException
+    {
+        MavenCli.ProjectActivation result;
+        Options options = new Options();
+        options.addOption( Option.builder( CLIManager.PROJECT_LIST ).hasArg().build() );
+
+        result = determineProjectActivation( new GnuParser().parse( options, new String[0]
) );
+        assertThat( result.activeProjects, is( nullValue() ) );
+        assertThat( result.inactiveProjects, is( nullValue() ) );
+
+        result = determineProjectActivation( new GnuParser().parse( options, new String[]{
"-pl", "test1,+test2" } ) );
+        assertThat( result.activeProjects.size(), is( 2 ) );
+        assertThat( result.activeProjects, contains( "test1", "test2" ) );
+
+        result = determineProjectActivation( new GnuParser().parse( options, new String[]{
"-pl", "!test1,-test2" } ) );
+        assertThat( result.inactiveProjects.size(), is( 2 ) );
+        assertThat( result.inactiveProjects, contains( "test1", "test2" ) );
+
+        result = determineProjectActivation( new GnuParser().parse( options, new String[]{
"-pl" ,"-test1,+test2" } ) );
+        assertThat( result.activeProjects.size(), is( 1 ) );
+        assertThat( result.activeProjects, contains( "test2" ) );
+        assertThat( result.inactiveProjects.size(), is( 1 ) );
+        assertThat( result.inactiveProjects, contains( "test1" ) );
+    }
+
+    @Test
     public void testCalculateDegreeOfConcurrencyWithCoreMultiplier()
     {
         int cores = Runtime.getRuntime().availableProcessors();


Mime
View raw message