This commit is contained in:
rfscholte 2020-10-21 21:25:41 +02:00
commit 8913502589
16 changed files with 772 additions and 174 deletions

View File

@ -21,7 +21,6 @@ package org.apache.maven.graph;
import java.io.File; import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
@ -36,7 +35,6 @@ import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.apache.maven.DefaultMaven;
import org.apache.maven.MavenExecutionException; import org.apache.maven.MavenExecutionException;
import org.apache.maven.ProjectCycleException; import org.apache.maven.ProjectCycleException;
import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.artifact.ArtifactUtils;
@ -46,20 +44,17 @@ import org.apache.maven.execution.MavenSession;
import org.apache.maven.execution.ProjectDependencyGraph; import org.apache.maven.execution.ProjectDependencyGraph;
import org.apache.maven.model.Plugin; import org.apache.maven.model.Plugin;
import org.apache.maven.model.building.DefaultModelProblem; import org.apache.maven.model.building.DefaultModelProblem;
import org.apache.maven.model.building.ModelProblem;
import org.apache.maven.model.building.ModelProblemUtils;
import org.apache.maven.model.building.ModelSource;
import org.apache.maven.model.building.Result; import org.apache.maven.model.building.Result;
import org.apache.maven.model.building.UrlModelSource;
import org.apache.maven.project.DuplicateProjectException; import org.apache.maven.project.DuplicateProjectException;
import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectBuilder;
import org.apache.maven.project.ProjectBuildingException; import org.apache.maven.project.ProjectBuildingException;
import org.apache.maven.project.ProjectBuildingRequest; import org.apache.maven.project.collector.MultiModuleCollectionStrategy;
import org.apache.maven.project.ProjectBuildingResult; import org.apache.maven.project.collector.PomlessCollectionStrategy;
import org.codehaus.plexus.logging.Logger; import org.apache.maven.project.collector.RequestPomCollectionStrategy;
import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.dag.CycleDetectedException; import org.codehaus.plexus.util.dag.CycleDetectedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static java.util.Comparator.comparing; import static java.util.Comparator.comparing;
@ -71,15 +66,24 @@ import static java.util.Comparator.comparing;
public class DefaultGraphBuilder public class DefaultGraphBuilder
implements GraphBuilder implements GraphBuilder
{ {
private static final Logger LOGGER = LoggerFactory.getLogger( DefaultGraphBuilder.class );
private final BuildResumptionDataRepository buildResumptionDataRepository;
private final PomlessCollectionStrategy pomlessCollectionStrategy;
private final MultiModuleCollectionStrategy multiModuleCollectionStrategy;
private final RequestPomCollectionStrategy requestPomCollectionStrategy;
@Inject @Inject
private Logger logger; public DefaultGraphBuilder( BuildResumptionDataRepository buildResumptionDataRepository,
PomlessCollectionStrategy pomlessCollectionStrategy,
@Inject MultiModuleCollectionStrategy multiModuleCollectionStrategy,
protected ProjectBuilder projectBuilder; RequestPomCollectionStrategy requestPomCollectionStrategy )
{
@Inject this.buildResumptionDataRepository = buildResumptionDataRepository;
private BuildResumptionDataRepository buildResumptionDataRepository; this.pomlessCollectionStrategy = pomlessCollectionStrategy;
this.multiModuleCollectionStrategy = multiModuleCollectionStrategy;
this.requestPomCollectionStrategy = requestPomCollectionStrategy;
}
@Override @Override
public Result<ProjectDependencyGraph> build( MavenSession session ) public Result<ProjectDependencyGraph> build( MavenSession session )
@ -91,7 +95,7 @@ public class DefaultGraphBuilder
if ( result == null ) if ( result == null )
{ {
final List<MavenProject> projects = getProjectsForMavenReactor( session ); final List<MavenProject> projects = getProjectsForMavenReactor( session );
validateProjects( projects ); validateProjects( projects, session.getRequest() );
enrichRequestFromResumptionData( projects, session.getRequest() ); enrichRequestFromResumptionData( projects, session.getRequest() );
result = reactorDependencyGraph( session, projects ); result = reactorDependencyGraph( session, projects );
} }
@ -133,6 +137,7 @@ public class DefaultGraphBuilder
{ {
ProjectDependencyGraph projectDependencyGraph = new DefaultProjectDependencyGraph( projects ); ProjectDependencyGraph projectDependencyGraph = new DefaultProjectDependencyGraph( projects );
List<MavenProject> activeProjects = projectDependencyGraph.getSortedProjects(); List<MavenProject> activeProjects = projectDependencyGraph.getSortedProjects();
activeProjects = trimProjectsToRequest( activeProjects, projectDependencyGraph, session.getRequest() );
activeProjects = trimSelectedProjects( activeProjects, projectDependencyGraph, session.getRequest() ); activeProjects = trimSelectedProjects( activeProjects, projectDependencyGraph, session.getRequest() );
activeProjects = trimResumedProjects( activeProjects, projectDependencyGraph, session.getRequest() ); activeProjects = trimResumedProjects( activeProjects, projectDependencyGraph, session.getRequest() );
activeProjects = trimExcludedProjects( activeProjects, session.getRequest() ); activeProjects = trimExcludedProjects( activeProjects, session.getRequest() );
@ -145,6 +150,26 @@ public class DefaultGraphBuilder
return Result.success( projectDependencyGraph ); return Result.success( projectDependencyGraph );
} }
private List<MavenProject> trimProjectsToRequest( List<MavenProject> activeProjects,
ProjectDependencyGraph graph,
MavenExecutionRequest request )
throws MavenExecutionException
{
List<MavenProject> result = activeProjects;
if ( request.getPom() != null )
{
result = getProjectsInRequestScope( request, activeProjects );
List<MavenProject> sortedProjects = graph.getSortedProjects();
result.sort( comparing( sortedProjects::indexOf ) );
result = includeAlsoMakeTransitively( result, request, graph );
}
return result;
}
private List<MavenProject> trimSelectedProjects( List<MavenProject> projects, ProjectDependencyGraph graph, private List<MavenProject> trimSelectedProjects( List<MavenProject> projects, ProjectDependencyGraph graph,
MavenExecutionRequest request ) MavenExecutionRequest request )
throws MavenExecutionException throws MavenExecutionException
@ -155,7 +180,7 @@ public class DefaultGraphBuilder
{ {
File reactorDirectory = getReactorDirectory( request ); File reactorDirectory = getReactorDirectory( request );
Collection<MavenProject> selectedProjects = new LinkedHashSet<>( request.getSelectedProjects().size(), 1 ); Collection<MavenProject> selectedProjects = new LinkedHashSet<>();
for ( String selector : request.getSelectedProjects() ) for ( String selector : request.getSelectedProjects() )
{ {
@ -165,6 +190,12 @@ public class DefaultGraphBuilder
.orElseThrow( () -> new MavenExecutionException( .orElseThrow( () -> new MavenExecutionException(
"Could not find the selected project in the reactor: " + selector, request.getPom() ) ); "Could not find the selected project in the reactor: " + selector, request.getPom() ) );
selectedProjects.add( selectedProject ); selectedProjects.add( selectedProject );
List<MavenProject> children = selectedProject.getCollectedProjects();
if ( children != null )
{
selectedProjects.addAll( children );
}
} }
result = new ArrayList<>( selectedProjects ); result = new ArrayList<>( selectedProjects );
@ -287,6 +318,28 @@ public class DefaultGraphBuilder
} }
} }
private List<MavenProject> getProjectsInRequestScope( MavenExecutionRequest request, List<MavenProject> projects )
throws MavenExecutionException
{
if ( request.getPom() == null )
{
return projects;
}
MavenProject requestPomProject = projects.stream()
.filter( project -> request.getPom().equals( project.getFile() ) )
.findFirst()
.orElseThrow( () -> new MavenExecutionException(
"Could not find a project in reactor matching the request POM", request.getPom() ) );
List<MavenProject> modules = requestPomProject.getCollectedProjects() != null
? requestPomProject.getCollectedProjects() : Collections.emptyList();
List<MavenProject> result = new ArrayList<>( modules );
result.add( requestPomProject );
return result;
}
private String formatProjects( List<MavenProject> projects ) private String formatProjects( List<MavenProject> projects )
{ {
StringBuilder projectNames = new StringBuilder(); StringBuilder projectNames = new StringBuilder();
@ -361,76 +414,32 @@ public class DefaultGraphBuilder
throws ProjectBuildingException throws ProjectBuildingException
{ {
MavenExecutionRequest request = session.getRequest(); MavenExecutionRequest request = session.getRequest();
request.getProjectBuildingRequest().setRepositorySession( session.getRepositorySession() ); request.getProjectBuildingRequest().setRepositorySession( session.getRepositorySession() );
List<MavenProject> projects = new ArrayList<>(); // 1. Collect project for invocation without a POM.
// We have no POM file.
//
if ( request.getPom() == null ) if ( request.getPom() == null )
{ {
ModelSource modelSource = new UrlModelSource( DefaultMaven.class.getResource( "project/standalone.xml" ) ); return pomlessCollectionStrategy.collectProjects( request );
MavenProject project = projectBuilder.build( modelSource, request.getProjectBuildingRequest() ) }
.getProject();
project.setExecutionRoot( true ); // 2. Collect projects for all modules in the multi-module project.
projects.add( project ); List<MavenProject> projects = multiModuleCollectionStrategy.collectProjects( request );
request.setProjectPresent( false ); if ( !projects.isEmpty() )
{
return projects; return projects;
} }
List<File> files = Arrays.asList( request.getPom().getAbsoluteFile() ); // 3. Collect projects for explicitly requested POM.
collectProjects( projects, files, request ); return requestPomCollectionStrategy.collectProjects( request );
return projects;
} }
private void collectProjects( List<MavenProject> projects, List<File> files, MavenExecutionRequest request ) private void validateProjects( List<MavenProject> projects, MavenExecutionRequest request )
throws ProjectBuildingException throws MavenExecutionException
{
ProjectBuildingRequest projectBuildingRequest = request.getProjectBuildingRequest();
List<ProjectBuildingResult> results = projectBuilder.build( files, request.isRecursive(),
projectBuildingRequest );
boolean problems = false;
for ( ProjectBuildingResult result : results )
{
projects.add( result.getProject() );
if ( !result.getProblems().isEmpty() && logger.isWarnEnabled() )
{
logger.warn( "" );
logger.warn( "Some problems were encountered while building the effective model for "
+ result.getProject().getId() );
for ( ModelProblem problem : result.getProblems() )
{
String loc = ModelProblemUtils.formatLocation( problem, result.getProjectId() );
logger.warn( problem.getMessage() + ( StringUtils.isNotEmpty( loc ) ? " @ " + loc : "" ) );
}
problems = true;
}
}
if ( problems )
{
logger.warn( "" );
logger.warn( "It is highly recommended to fix these problems"
+ " because they threaten the stability of your build." );
logger.warn( "" );
logger.warn( "For this reason, future Maven versions might no"
+ " longer support building such malformed projects." );
logger.warn( "" );
}
}
private void validateProjects( List<MavenProject> projects )
{ {
Map<String, MavenProject> projectsMap = new HashMap<>(); Map<String, MavenProject> projectsMap = new HashMap<>();
for ( MavenProject p : projects ) List<MavenProject> projectsInRequestScope = getProjectsInRequestScope( request, projects );
for ( MavenProject p : projectsInRequestScope )
{ {
String projectKey = ArtifactUtils.key( p.getGroupId(), p.getArtifactId(), p.getVersion() ); String projectKey = ArtifactUtils.key( p.getGroupId(), p.getArtifactId(), p.getVersion() );
@ -449,9 +458,8 @@ public class DefaultGraphBuilder
if ( projectsMap.containsKey( pluginKey ) ) if ( projectsMap.containsKey( pluginKey ) )
{ {
logger.warn( project.getName() + " uses " + plugin.getKey() LOGGER.warn( "{} uses {} as extensions, which is not possible within the same reactor build. "
+ " as extensions, which is not possible within the same reactor build. " + "This plugin was pulled from the local repository!", project.getName(), plugin.getKey() );
+ "This plugin was pulled from the local repository!" );
} }
} }
} }

View File

@ -106,7 +106,7 @@ public class DefaultModelBuildingListener
catch ( PluginResolutionException | PluginManagerException | PluginVersionResolutionException e ) catch ( PluginResolutionException | PluginManagerException | PluginVersionResolutionException e )
{ {
event.getProblems().add( new ModelProblemCollectorRequest( Severity.ERROR, Version.BASE ) event.getProblems().add( new ModelProblemCollectorRequest( Severity.ERROR, Version.BASE )
.setMessage( "Unresolveable build extension: " + e.getMessage() ) .setMessage( "Unresolvable build extension: " + e.getMessage() )
.setException( e ) ); .setException( e ) );
} }

View File

@ -0,0 +1,98 @@
package org.apache.maven.project.collector;
/*
* 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.execution.MavenExecutionRequest;
import org.apache.maven.model.building.ModelProblem;
import org.apache.maven.model.building.ModelProblemUtils;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectBuilder;
import org.apache.maven.project.ProjectBuildingException;
import org.apache.maven.project.ProjectBuildingRequest;
import org.apache.maven.project.ProjectBuildingResult;
import org.codehaus.plexus.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import java.io.File;
import java.util.List;
/**
* Utility to collect projects for a given set of pom.xml files.
*/
@Named
@Singleton
public class DefaultProjectsCollector implements ProjectsCollector
{
private static final Logger LOGGER = LoggerFactory.getLogger( DefaultProjectsCollector.class );
private final ProjectBuilder projectBuilder;
@Inject
public DefaultProjectsCollector( ProjectBuilder projectBuilder )
{
this.projectBuilder = projectBuilder;
}
@Override
public void collectProjects( List<MavenProject> projects, List<File> files, MavenExecutionRequest request )
throws ProjectBuildingException
{
ProjectBuildingRequest projectBuildingRequest = request.getProjectBuildingRequest();
List<ProjectBuildingResult> results = projectBuilder.build( files, request.isRecursive(),
projectBuildingRequest );
boolean problems = false;
for ( ProjectBuildingResult result : results )
{
projects.add( result.getProject() );
if ( !result.getProblems().isEmpty() && LOGGER.isWarnEnabled() )
{
LOGGER.warn( "" );
LOGGER.warn( "Some problems were encountered while building the effective model for {}",
result.getProject().getId() );
for ( ModelProblem problem : result.getProblems() )
{
String loc = ModelProblemUtils.formatLocation( problem, result.getProjectId() );
LOGGER.warn( "{}{}", problem.getMessage(), ( StringUtils.isNotEmpty( loc ) ? " @ " + loc : "" ) );
}
problems = true;
}
}
if ( problems )
{
LOGGER.warn( "" );
LOGGER.warn( "It is highly recommended to fix these problems"
+ " because they threaten the stability of your build." );
LOGGER.warn( "" );
LOGGER.warn( "For this reason, future Maven versions might no"
+ " longer support building such malformed projects." );
LOGGER.warn( "" );
}
}
}

View File

@ -0,0 +1,195 @@
package org.apache.maven.project.collector;
/*
* 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.execution.MavenExecutionRequest;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.building.ModelProblem;
import org.apache.maven.model.locator.ModelLocator;
import org.apache.maven.plugin.PluginManagerException;
import org.apache.maven.plugin.PluginResolutionException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectBuildingException;
import org.apache.maven.project.ProjectBuildingResult;
import org.eclipse.aether.resolution.ArtifactResolutionException;
import org.eclipse.aether.transfer.ArtifactNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;
/**
* Strategy for collecting Maven projects from the multi-module project root, even when executed in a submodule.
*/
@Named( "MultiModuleCollectionStrategy" )
@Singleton
public class MultiModuleCollectionStrategy implements ProjectCollectionStrategy
{
private final Logger logger = LoggerFactory.getLogger( getClass() );
private final ModelLocator modelLocator;
private final ProjectsCollector projectsCollector;
@Inject
public MultiModuleCollectionStrategy( ModelLocator modelLocator, ProjectsCollector projectsCollector )
{
this.modelLocator = modelLocator;
this.projectsCollector = projectsCollector;
}
@Override
public List<MavenProject> collectProjects( MavenExecutionRequest request ) throws ProjectBuildingException
{
File moduleProjectPomFile = getMultiModuleProjectPomFile( request );
List<File> files = Collections.singletonList( moduleProjectPomFile.getAbsoluteFile() );
try
{
List<MavenProject> projects = new ArrayList<>();
projectsCollector.collectProjects( projects, files, request );
boolean isRequestedProjectCollected = isRequestedProjectCollected( request, projects );
if ( isRequestedProjectCollected )
{
return projects;
}
else
{
logger.debug( "Multi module project collection failed: {}"
+ "Detected a POM file next to a .mvn folder in a parent directory ({}). "
+ "Maven assumed that POM file to be the parent of the requested project ({}), but it turned "
+ "out that it was not. Another project collection strategy will be executed as result.",
System.lineSeparator(), moduleProjectPomFile.getAbsolutePath(),
request.getPom().getAbsolutePath() );
return Collections.emptyList();
}
}
catch ( ProjectBuildingException e )
{
boolean fallThrough = isModuleOutsideRequestScopeDependingOnPluginModule( request, e );
if ( fallThrough )
{
logger.debug( "Multi module project collection failed: {}"
+ "Detected that one of the modules of this multi module project uses another module as "
+ "plugin extension which still needed to be built. This is not possible within the same "
+ "reactor build. Another project collection strategy will be executed as result.",
System.lineSeparator() );
return Collections.emptyList();
}
throw e;
}
}
private File getMultiModuleProjectPomFile( MavenExecutionRequest request )
{
if ( request.getPom().getParentFile().equals( request.getMultiModuleProjectDirectory() ) )
{
return request.getPom();
}
else
{
File multiModuleProjectPom = modelLocator.locatePom( request.getMultiModuleProjectDirectory() );
if ( !multiModuleProjectPom.exists() )
{
logger.info( "Maven detected that the requested POM file is part of a multi module project, "
+ "but could not find a pom.xml file in the multi module root directory: '"
+ request.getMultiModuleProjectDirectory() + "'. " );
logger.info( "The reactor is limited to all projects under: " + request.getPom().getParent() );
return request.getPom();
}
return multiModuleProjectPom;
}
}
/**
* multiModuleProjectDirectory in MavenExecutionRequest is not always the parent of the request pom.
* We should always check whether the request pom project is collected.
* The integration tests for MNG-6223 are examples for this scenario.
*
* @return true if the collected projects contain the requested project (for example with -f)
*/
private boolean isRequestedProjectCollected( MavenExecutionRequest request, List<MavenProject> projects )
{
return projects.stream()
.map( MavenProject::getFile )
.anyMatch( request.getPom()::equals );
}
/**
* This method finds out whether collecting projects failed because of the following scenario:
* - A multi module project containing a module which is a plugin and another module which depends on it.
* - Just the plugin is being built with the -f <pom> flag.
* - Because of inter-module dependency collection, all projects in the multi-module project are collected.
* - The plugin is not yet installed in a repository.
*
* Therefore the build fails because the plugin is not found and plugins cannot be built in the same session.
*
* The integration test for <a href="https://issues.apache.org/jira/browse/MNG-5572">MNG-5572</a> is an
* example of this scenario.
*
* @return true if the module which fails to collect the inter-module plugin is not part of the build.
*/
private boolean isModuleOutsideRequestScopeDependingOnPluginModule( MavenExecutionRequest request,
ProjectBuildingException exception )
{
return exception.getResults().stream()
.map( ProjectBuildingResult::getProject )
.filter( Objects::nonNull )
.filter( project -> request.getPom().equals( project.getFile() ) )
.findFirst()
.map( requestPomProject ->
{
List<MavenProject> modules = requestPomProject.getCollectedProjects() != null
? requestPomProject.getCollectedProjects() : Collections.emptyList();
List<MavenProject> projectsInRequestScope = new ArrayList<>( modules );
projectsInRequestScope.add( requestPomProject );
Predicate<ProjectBuildingResult> projectsOutsideOfRequestScope =
pr -> !projectsInRequestScope.contains( pr.getProject() );
Predicate<Exception> pluginArtifactNotFoundException =
exc -> exc instanceof PluginManagerException
&& exc.getCause() instanceof PluginResolutionException
&& exc.getCause().getCause() instanceof ArtifactResolutionException
&& exc.getCause().getCause().getCause() instanceof ArtifactNotFoundException;
Predicate<Plugin> isPluginPartOfRequestScope = plugin -> projectsInRequestScope.stream()
.anyMatch( project -> project.getGroupId().equals( plugin.getGroupId() )
&& project.getArtifactId().equals( plugin.getArtifactId() )
&& project.getVersion().equals( plugin.getVersion() ) );
return exception.getResults().stream()
.filter( projectsOutsideOfRequestScope )
.flatMap( projectBuildingResult -> projectBuildingResult.getProblems().stream() )
.map( ModelProblem::getException )
.filter( pluginArtifactNotFoundException )
.map( exc -> ( ( PluginResolutionException ) exc.getCause() ).getPlugin() )
.anyMatch( isPluginPartOfRequestScope );
} ).orElse( false );
}
}

View File

@ -0,0 +1,67 @@
package org.apache.maven.project.collector;
/*
* 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.DefaultMaven;
import org.apache.maven.execution.MavenExecutionRequest;
import org.apache.maven.model.building.ModelSource;
import org.apache.maven.model.building.UrlModelSource;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectBuilder;
import org.apache.maven.project.ProjectBuildingException;
import org.apache.maven.project.ProjectBuildingRequest;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
/**
* Strategy to collect projects for building when the Maven invocation is not in a folder that contains a pom.xml.
*/
@Named( "PomlessCollectionStrategy" )
@Singleton
public class PomlessCollectionStrategy
implements ProjectCollectionStrategy
{
private final ProjectBuilder projectBuilder;
@Inject
public PomlessCollectionStrategy( ProjectBuilder projectBuilder )
{
this.projectBuilder = projectBuilder;
}
@Override
public List<MavenProject> collectProjects( final MavenExecutionRequest request )
throws ProjectBuildingException
{
ProjectBuildingRequest buildingRequest = request.getProjectBuildingRequest();
ModelSource modelSource = new UrlModelSource( DefaultMaven.class.getResource( "project/standalone.xml" ) );
MavenProject project = projectBuilder.build( modelSource, buildingRequest ).getProject();
project.setExecutionRoot( true );
request.setProjectPresent( false );
final List<MavenProject> result = new ArrayList<>();
result.add( project );
return result;
}
}

View File

@ -0,0 +1,41 @@
package org.apache.maven.project.collector;
/*
* 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.execution.MavenExecutionRequest;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectBuildingException;
import java.util.List;
/**
* Describes strategies for finding projects that Maven could build.
*/
public interface ProjectCollectionStrategy
{
/**
*
* @param request
* @return
* @throws ProjectBuildingException
*/
List<MavenProject> collectProjects( final MavenExecutionRequest request )
throws ProjectBuildingException;
}

View File

@ -0,0 +1,43 @@
package org.apache.maven.project.collector;
/*
* 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.execution.MavenExecutionRequest;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectBuildingException;
import java.io.File;
import java.util.List;
/**
* Facade to collect projects for a given set of pom.xml files.
*/
public interface ProjectsCollector
{
/**
* Collect Maven projects from a list of POM files.
* @param projects List that will be filled with the found projects.
* @param files List of POM files.
* @param request The {@link MavenExecutionRequest}
* @throws ProjectBuildingException In case the POMs are not used.
*/
void collectProjects( List<MavenProject> projects, List<File> files, MavenExecutionRequest request )
throws ProjectBuildingException;
}

View File

@ -0,0 +1,57 @@
package org.apache.maven.project.collector;
/*
* 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.execution.MavenExecutionRequest;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectBuildingException;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Strategy to collect projects based on the <code>-f</code> CLI parameter or the pom.xml in the working directory.
*/
@Named( "RequestPomCollectionStrategy" )
@Singleton
public class RequestPomCollectionStrategy implements ProjectCollectionStrategy
{
private final ProjectsCollector projectsCollector;
@Inject
public RequestPomCollectionStrategy( ProjectsCollector projectsCollector )
{
this.projectsCollector = projectsCollector;
}
@Override
public List<MavenProject> collectProjects( MavenExecutionRequest request ) throws ProjectBuildingException
{
List<File> files = Collections.singletonList( request.getPom().getAbsoluteFile() );
List<MavenProject> projects = new ArrayList<>();
projectsCollector.collectProjects( projects, files, request );
return projects;
}
}

View File

@ -116,6 +116,11 @@ public abstract class AbstractCoreMavenComponentTestCase
.setPluginArtifactRepositories( getPluginArtifactRepositories() ) .setPluginArtifactRepositories( getPluginArtifactRepositories() )
.setGoals( Arrays.asList( "package" ) ); .setGoals( Arrays.asList( "package" ) );
if ( pom != null )
{
request.setMultiModuleProjectDirectory( pom.getParentFile() );
}
return request; return request;
} }

View File

@ -19,37 +19,45 @@ package org.apache.maven.graph;
* under the License. * under the License.
*/ */
import com.google.common.collect.ImmutableMap; import org.apache.maven.execution.BuildResumptionDataRepository;
import org.apache.maven.execution.MavenExecutionRequest; import org.apache.maven.execution.MavenExecutionRequest;
import org.apache.maven.execution.MavenSession; import org.apache.maven.execution.MavenSession;
import org.apache.maven.execution.ProjectDependencyGraph; import org.apache.maven.execution.ProjectDependencyGraph;
import org.apache.maven.model.Dependency; import org.apache.maven.model.Dependency;
import org.apache.maven.model.Parent;
import org.apache.maven.model.building.Result; import org.apache.maven.model.building.Result;
import org.apache.maven.model.locator.DefaultModelLocator;
import org.apache.maven.model.locator.ModelLocator;
import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectBuilder; import org.apache.maven.project.ProjectBuilder;
import org.apache.maven.project.ProjectBuildingRequest; import org.apache.maven.project.ProjectBuildingRequest;
import org.apache.maven.project.ProjectBuildingResult; import org.apache.maven.project.ProjectBuildingResult;
import org.apache.maven.project.collector.DefaultProjectsCollector;
import org.apache.maven.project.collector.MultiModuleCollectionStrategy;
import org.apache.maven.project.collector.PomlessCollectionStrategy;
import org.apache.maven.project.collector.ProjectsCollector;
import org.apache.maven.project.collector.RequestPomCollectionStrategy;
import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.StringUtils;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.Parameterized; import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters; import org.junit.runners.Parameterized.Parameters;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.io.File; import java.io.File;
import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Arrays.asList; import static java.util.Arrays.asList;
import static java.util.Collections.emptyList; import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList; import static java.util.Collections.singletonList;
import static java.util.function.Function.identity;
import static junit.framework.TestCase.assertEquals; import static junit.framework.TestCase.assertEquals;
import static org.apache.maven.execution.MavenExecutionRequest.*; import static org.apache.maven.execution.MavenExecutionRequest.REACTOR_MAKE_DOWNSTREAM;
import static org.apache.maven.execution.MavenExecutionRequest.REACTOR_MAKE_UPSTREAM; import static org.apache.maven.execution.MavenExecutionRequest.REACTOR_MAKE_UPSTREAM;
import static org.apache.maven.graph.DefaultGraphBuilderTest.ScenarioBuilder.scenario; import static org.apache.maven.graph.DefaultGraphBuilderTest.ScenarioBuilder.scenario;
import static org.mockito.ArgumentMatchers.*; import static org.mockito.ArgumentMatchers.*;
@ -59,22 +67,39 @@ import static org.mockito.Mockito.when;
@RunWith( Parameterized.class ) @RunWith( Parameterized.class )
public class DefaultGraphBuilderTest public class DefaultGraphBuilderTest
{ {
/*
The multi-module structure in this project is displayed as follows:
module-parent
module-independent (without parent declaration)
module-a
module-b (depends on module-a)
module-c
module-c-1
module-c-2 (depends on module-b)
*/
private static final String PARENT_MODULE = "module-parent";
private static final String INDEPENDENT_MODULE = "module-independent"; private static final String INDEPENDENT_MODULE = "module-independent";
private static final String MODULE_A = "module-a"; private static final String MODULE_A = "module-a";
private static final String MODULE_B = "module-b"; // depends on module-a private static final String MODULE_B = "module-b";
private static final String MODULE_C = "module-c"; // depends on module-b private static final String MODULE_C = "module-c";
private static final String MODULE_C_1 = "module-c-1";
private static final String MODULE_C_2 = "module-c-2";
@InjectMocks
private DefaultGraphBuilder graphBuilder; private DefaultGraphBuilder graphBuilder;
@Mock private final ProjectBuilder projectBuilder = mock( ProjectBuilder.class );
private ProjectBuilder projectBuilder; private final MavenSession session = mock( MavenSession.class );
private final MavenExecutionRequest mavenExecutionRequest = mock( MavenExecutionRequest.class );
@Mock private final ProjectsCollector projectsCollector = new DefaultProjectsCollector( projectBuilder );
private MavenSession session;
@Mock // Not using mocks for these strategies - a mock would just copy the actual implementation.
private MavenExecutionRequest mavenExecutionRequest;
private final ModelLocator modelLocator = new DefaultModelLocator();
private final PomlessCollectionStrategy pomlessCollectionStrategy = new PomlessCollectionStrategy( projectBuilder );
private final MultiModuleCollectionStrategy multiModuleCollectionStrategy = new MultiModuleCollectionStrategy( modelLocator, projectsCollector );
private final RequestPomCollectionStrategy requestPomCollectionStrategy = new RequestPomCollectionStrategy( projectsCollector );
private Map<String, MavenProject> artifactIdProjectMap; private Map<String, MavenProject> artifactIdProjectMap;
@ -85,73 +110,85 @@ public class DefaultGraphBuilderTest
private final String parameterResumeFrom; private final String parameterResumeFrom;
private final String parameterMakeBehavior; private final String parameterMakeBehavior;
private final List<String> parameterExpectedResult; private final List<String> parameterExpectedResult;
private final File parameterRequestedPom;
@Parameters(name = "{index}. {0}") @Parameters(name = "{index}. {0}")
public static Collection<Object[]> parameters() public static Collection<Object[]> parameters()
{ {
return asList( return asList(
scenario( "Full reactor" ) scenario( "Full reactor in order" )
.expectResult( asList( INDEPENDENT_MODULE, MODULE_A, MODULE_B, MODULE_C ) ), .expectResult( PARENT_MODULE, MODULE_C, MODULE_C_1, MODULE_A, MODULE_B, MODULE_C_2, INDEPENDENT_MODULE ),
scenario( "Selected project" ) scenario( "Selected project" )
.selectedProjects( singletonList( MODULE_B ) ) .selectedProjects( MODULE_B )
.expectResult( singletonList( MODULE_B ) ), .expectResult( MODULE_B ),
scenario( "Excluded project" ) scenario( "Excluded project" )
.excludedProjects( singletonList( MODULE_B ) ) .excludedProjects( MODULE_B )
.expectResult( asList( INDEPENDENT_MODULE, MODULE_A, MODULE_C ) ), .expectResult( PARENT_MODULE, MODULE_C, MODULE_C_1, MODULE_A, MODULE_C_2, INDEPENDENT_MODULE ),
scenario( "Resuming from project" ) scenario( "Resuming from project" )
.resumeFrom( MODULE_B ) .resumeFrom( MODULE_B )
.expectResult( asList( MODULE_B, MODULE_C ) ), .expectResult( MODULE_B, MODULE_C_2, INDEPENDENT_MODULE ),
scenario( "Selected project with also make dependencies" ) scenario( "Selected project with also make dependencies" )
.selectedProjects( singletonList( MODULE_C ) ) .selectedProjects( MODULE_C_2 )
.makeBehavior( REACTOR_MAKE_UPSTREAM ) .makeBehavior( REACTOR_MAKE_UPSTREAM )
.expectResult( asList( MODULE_A, MODULE_B, MODULE_C ) ), .expectResult( PARENT_MODULE, MODULE_C, MODULE_A, MODULE_B, MODULE_C_2 ),
scenario( "Selected project with also make dependents" ) scenario( "Selected project with also make dependents" )
.selectedProjects( singletonList( MODULE_B ) ) .selectedProjects( MODULE_B )
.makeBehavior( REACTOR_MAKE_DOWNSTREAM ) .makeBehavior( REACTOR_MAKE_DOWNSTREAM )
.expectResult( asList( MODULE_B, MODULE_C ) ), .expectResult( MODULE_B, MODULE_C_2 ),
scenario( "Resuming from project with also make dependencies" ) scenario( "Resuming from project with also make dependencies" )
.makeBehavior( REACTOR_MAKE_UPSTREAM ) .makeBehavior( REACTOR_MAKE_UPSTREAM )
.resumeFrom( MODULE_C ) .resumeFrom( MODULE_C_2 )
.expectResult( asList( MODULE_A, MODULE_B, MODULE_C ) ), .expectResult( PARENT_MODULE, MODULE_C, MODULE_A, MODULE_B, MODULE_C_2, INDEPENDENT_MODULE ),
scenario( "Selected project with resume from an also make dependency (MNG-4960 IT#1)" ) scenario( "Selected project with resume from and also make dependency (MNG-4960 IT#1)" )
.selectedProjects( singletonList( MODULE_C ) ) .selectedProjects( MODULE_C_2 )
.resumeFrom( MODULE_B ) .resumeFrom( MODULE_B )
.makeBehavior( REACTOR_MAKE_UPSTREAM ) .makeBehavior( REACTOR_MAKE_UPSTREAM )
.expectResult( asList( MODULE_A, MODULE_B, MODULE_C ) ), .expectResult( PARENT_MODULE, MODULE_C, MODULE_A, MODULE_B, MODULE_C_2 ),
scenario( "Selected project with resume from an also make dependent (MNG-4960 IT#2)" ) scenario( "Selected project with resume from and also make dependent (MNG-4960 IT#2)" )
.selectedProjects( singletonList( MODULE_B ) ) .selectedProjects( MODULE_B )
.resumeFrom( MODULE_C ) .resumeFrom( MODULE_C_2 )
.makeBehavior( REACTOR_MAKE_DOWNSTREAM ) .makeBehavior( REACTOR_MAKE_DOWNSTREAM )
.expectResult( singletonList( MODULE_C ) ), .expectResult( MODULE_C_2 ),
scenario( "Excluding an also make dependency from selectedProject does take its transitive dependency" ) scenario( "Excluding an also make dependency from selectedProject does take its transitive dependency" )
.selectedProjects( singletonList( MODULE_C ) ) .selectedProjects( MODULE_C_2 )
.excludedProjects( singletonList( MODULE_B ) ) .excludedProjects( MODULE_B )
.makeBehavior( REACTOR_MAKE_UPSTREAM ) .makeBehavior( REACTOR_MAKE_UPSTREAM )
.expectResult( asList( MODULE_A, MODULE_C ) ), .expectResult( PARENT_MODULE, MODULE_C, MODULE_A, MODULE_C_2 ),
scenario( "Excluding an also make dependency from resumeFrom does take its transitive dependency" ) scenario( "Excluding an also make dependency from resumeFrom does take its transitive dependency" )
.resumeFrom( MODULE_C ) .resumeFrom( MODULE_C_2 )
.excludedProjects( singletonList( MODULE_B ) ) .excludedProjects( MODULE_B )
.makeBehavior( REACTOR_MAKE_UPSTREAM ) .makeBehavior( REACTOR_MAKE_UPSTREAM )
.expectResult( asList( MODULE_A, MODULE_C ) ), .expectResult( PARENT_MODULE, MODULE_C, MODULE_A, MODULE_C_2, INDEPENDENT_MODULE ),
scenario( "Resume from exclude project downstream" ) scenario( "Resume from exclude project downstream" )
.resumeFrom( MODULE_A ) .resumeFrom( MODULE_A )
.excludedProjects( singletonList( MODULE_B ) ) .excludedProjects( MODULE_B )
.expectResult( asList( MODULE_A, MODULE_C ) ), .expectResult( MODULE_A, MODULE_C_2, INDEPENDENT_MODULE ),
scenario( "Exclude the project we are resuming from (as proposed in MNG-6676)" ) scenario( "Exclude the project we are resuming from (as proposed in MNG-6676)" )
.resumeFrom( MODULE_B ) .resumeFrom( MODULE_B )
.excludedProjects( singletonList( MODULE_B ) ) .excludedProjects( MODULE_B )
.expectResult( singletonList( MODULE_C ) ), .expectResult( MODULE_C_2, INDEPENDENT_MODULE ),
scenario( "Selected projects in wrong order are resumed correctly in order" ) scenario( "Selected projects in wrong order are resumed correctly in order" )
.selectedProjects( asList( MODULE_C, MODULE_B, MODULE_A ) ) .selectedProjects( MODULE_C_2, MODULE_B, MODULE_A )
.resumeFrom( MODULE_B ) .resumeFrom( MODULE_B )
.expectResult( asList( MODULE_B, MODULE_C ) ), .expectResult( MODULE_B, MODULE_C_2 ),
scenario( "Duplicate projects are filtered out" ) scenario( "Duplicate projects are filtered out" )
.selectedProjects( asList( MODULE_A, MODULE_A ) ) .selectedProjects( MODULE_A, MODULE_A )
.expectResult( singletonList( MODULE_A ) ) .expectResult( MODULE_A ),
scenario( "Select reactor by specific pom" )
.requestedPom( MODULE_C )
.expectResult( MODULE_C, MODULE_C_1, MODULE_C_2 ),
scenario( "Select reactor by specific pom with also make dependencies" )
.requestedPom( MODULE_C )
.makeBehavior( REACTOR_MAKE_UPSTREAM )
.expectResult( PARENT_MODULE, MODULE_C, MODULE_C_1, MODULE_A, MODULE_B, MODULE_C_2 ),
scenario( "Select reactor by specific pom with also make dependents" )
.requestedPom( MODULE_B )
.makeBehavior( REACTOR_MAKE_DOWNSTREAM )
.expectResult( MODULE_B, MODULE_C_2 )
); );
} }
public DefaultGraphBuilderTest( String description, List<String> selectedProjects, List<String> excludedProjects, String resumedFrom, String makeBehavior, List<String> expectedReactorProjects ) public DefaultGraphBuilderTest( String description, List<String> selectedProjects, List<String> excludedProjects, String resumedFrom, String makeBehavior, List<String> expectedReactorProjects, File requestedPom )
{ {
this.parameterDescription = description; this.parameterDescription = description;
this.parameterSelectedProjects = selectedProjects; this.parameterSelectedProjects = selectedProjects;
@ -159,6 +196,7 @@ public class DefaultGraphBuilderTest
this.parameterResumeFrom = resumedFrom; this.parameterResumeFrom = resumedFrom;
this.parameterMakeBehavior = makeBehavior; this.parameterMakeBehavior = makeBehavior;
this.parameterExpectedResult = expectedReactorProjects; this.parameterExpectedResult = expectedReactorProjects;
this.parameterRequestedPom = requestedPom;
} }
@Test @Test
@ -171,6 +209,7 @@ public class DefaultGraphBuilderTest
when( mavenExecutionRequest.getSelectedProjects() ).thenReturn( selectedProjects ); when( mavenExecutionRequest.getSelectedProjects() ).thenReturn( selectedProjects );
when( mavenExecutionRequest.getExcludedProjects() ).thenReturn( excludedProjects ); when( mavenExecutionRequest.getExcludedProjects() ).thenReturn( excludedProjects );
when( mavenExecutionRequest.getMakeBehavior() ).thenReturn( parameterMakeBehavior ); when( mavenExecutionRequest.getMakeBehavior() ).thenReturn( parameterMakeBehavior );
when( mavenExecutionRequest.getPom() ).thenReturn( parameterRequestedPom );
if ( StringUtils.isNotEmpty( parameterResumeFrom ) ) if ( StringUtils.isNotEmpty( parameterResumeFrom ) )
{ {
when( mavenExecutionRequest.getResumeFrom() ).thenReturn( ":" + parameterResumeFrom ); when( mavenExecutionRequest.getResumeFrom() ).thenReturn( ":" + parameterResumeFrom );
@ -190,40 +229,47 @@ public class DefaultGraphBuilderTest
@Before @Before
public void before() throws Exception public void before() throws Exception
{ {
MockitoAnnotations.initMocks( this ); graphBuilder = new DefaultGraphBuilder(
mock( BuildResumptionDataRepository.class ),
pomlessCollectionStrategy,
multiModuleCollectionStrategy,
requestPomCollectionStrategy
);
ProjectBuildingRequest projectBuildingRequest = mock( ProjectBuildingRequest.class ); // Create projects
ProjectBuildingResult projectBuildingResult1 = mock( ProjectBuildingResult.class ); MavenProject projectParent = getMavenProject( PARENT_MODULE );
ProjectBuildingResult projectBuildingResult2 = mock( ProjectBuildingResult.class ); MavenProject projectIndependentModule = getMavenProject( INDEPENDENT_MODULE );
ProjectBuildingResult projectBuildingResult3 = mock( ProjectBuildingResult.class ); MavenProject projectModuleA = getMavenProject( MODULE_A, projectParent );
ProjectBuildingResult projectBuildingResult4 = mock( ProjectBuildingResult.class ); MavenProject projectModuleB = getMavenProject( MODULE_B, projectParent );
MavenProject projectIndependentModule = getMavenProject( "independent-module" ); MavenProject projectModuleC = getMavenProject( MODULE_C, projectParent );
MavenProject projectModuleA = getMavenProject( "module-a" ); MavenProject projectModuleC1 = getMavenProject( MODULE_C_1, projectModuleC );
MavenProject projectModuleB = getMavenProject( "module-b" ); MavenProject projectModuleC2 = getMavenProject( MODULE_C_2, projectModuleC );
MavenProject projectModuleC = getMavenProject( "module-c" );
projectModuleB.setDependencies( singletonList( toDependency( projectModuleA) ) );
projectModuleC.setDependencies( singletonList( toDependency( projectModuleB) ) );
artifactIdProjectMap = Stream.of( projectParent, projectIndependentModule, projectModuleA, projectModuleB, projectModuleC, projectModuleC1, projectModuleC2 )
.collect( Collectors.toMap( MavenProject::getArtifactId, identity() ) );
// Set dependencies and modules
projectModuleB.setDependencies( singletonList( toDependency( projectModuleA ) ) );
projectModuleC2.setDependencies( singletonList( toDependency( projectModuleB ) ) );
projectParent.setCollectedProjects( asList( projectIndependentModule, projectModuleA, projectModuleB, projectModuleC, projectModuleC1, projectModuleC2 ) );
projectModuleC.setCollectedProjects( asList( projectModuleC1, projectModuleC2 ) );
// Set up needed mocks
when( session.getRequest() ).thenReturn( mavenExecutionRequest ); when( session.getRequest() ).thenReturn( mavenExecutionRequest );
when( session.getProjects() ).thenReturn( null ); // needed, otherwise it will be an empty list by default when( session.getProjects() ).thenReturn( null ); // needed, otherwise it will be an empty list by default
when( mavenExecutionRequest.getProjectBuildingRequest() ).thenReturn( mock( ProjectBuildingRequest.class ) );
List<ProjectBuildingResult> projectBuildingResults = createProjectBuildingResultMocks( artifactIdProjectMap.values() );
when( projectBuilder.build( anyList(), anyBoolean(), any( ProjectBuildingRequest.class ) ) ).thenReturn( projectBuildingResults );
}
when( mavenExecutionRequest.getProjectBuildingRequest() ).thenReturn( projectBuildingRequest ); private MavenProject getMavenProject( String artifactId, MavenProject parentProject )
when( mavenExecutionRequest.getPom() ).thenReturn( new File( "/tmp/unit-test" ) ); {
MavenProject project = getMavenProject( artifactId );
when( projectBuildingResult1.getProject() ).thenReturn( projectIndependentModule ); Parent parent = new Parent();
when( projectBuildingResult2.getProject() ).thenReturn( projectModuleA ); parent.setGroupId( parentProject.getGroupId() );
when( projectBuildingResult3.getProject() ).thenReturn( projectModuleB ); parent.setArtifactId( parentProject.getArtifactId() );
when( projectBuildingResult4.getProject() ).thenReturn( projectModuleC ); project.getModel().setParent( parent );
return project;
when( projectBuilder.build( anyList(), anyBoolean(), any( ProjectBuildingRequest.class ) ) )
.thenReturn( asList( projectBuildingResult1, projectBuildingResult2, projectBuildingResult3, projectBuildingResult4 ) );
artifactIdProjectMap = ImmutableMap.of(
INDEPENDENT_MODULE, projectIndependentModule,
MODULE_A, projectModuleA,
MODULE_B, projectModuleB,
MODULE_C, projectModuleC
);
} }
private MavenProject getMavenProject( String artifactId ) private MavenProject getMavenProject( String artifactId )
@ -232,6 +278,8 @@ public class DefaultGraphBuilderTest
mavenProject.setGroupId( "unittest" ); mavenProject.setGroupId( "unittest" );
mavenProject.setArtifactId( artifactId ); mavenProject.setArtifactId( artifactId );
mavenProject.setVersion( "1.0" ); mavenProject.setVersion( "1.0" );
mavenProject.setPomFile( new File ( artifactId, "pom.xml" ) );
mavenProject.setCollectedProjects( new ArrayList<>() );
return mavenProject; return mavenProject;
} }
@ -244,6 +292,17 @@ public class DefaultGraphBuilderTest
return dependency; return dependency;
} }
private List<ProjectBuildingResult> createProjectBuildingResultMocks( Collection<MavenProject> projects )
{
return projects.stream()
.map( project -> {
ProjectBuildingResult result = mock( ProjectBuildingResult.class );
when( result.getProject() ).thenReturn( project );
return result;
} )
.collect( Collectors.toList() );
}
static class ScenarioBuilder static class ScenarioBuilder
{ {
private String description; private String description;
@ -251,6 +310,7 @@ public class DefaultGraphBuilderTest
private List<String> excludedProjects = emptyList(); private List<String> excludedProjects = emptyList();
private String resumeFrom = ""; private String resumeFrom = "";
private String makeBehavior = ""; private String makeBehavior = "";
private File requestedPom = new File( PARENT_MODULE, "pom.xml" );
private ScenarioBuilder() { } private ScenarioBuilder() { }
@ -261,15 +321,15 @@ public class DefaultGraphBuilderTest
return scenarioBuilder; return scenarioBuilder;
} }
public ScenarioBuilder selectedProjects( List<String> selectedProjects ) public ScenarioBuilder selectedProjects( String... selectedProjects )
{ {
this.selectedProjects = selectedProjects; this.selectedProjects = asList( selectedProjects );
return this; return this;
} }
public ScenarioBuilder excludedProjects( List<String> excludedProjects ) public ScenarioBuilder excludedProjects( String... excludedProjects )
{ {
this.excludedProjects = excludedProjects; this.excludedProjects = asList( excludedProjects );
return this; return this;
} }
@ -285,10 +345,16 @@ public class DefaultGraphBuilderTest
return this; return this;
} }
public Object[] expectResult( List<String> expectedReactorProjects ) public ScenarioBuilder requestedPom( String requestedPom )
{
this.requestedPom = new File( requestedPom, "pom.xml" );
return this;
}
public Object[] expectResult( String... expectedReactorProjects )
{ {
return new Object[] { return new Object[] {
description, selectedProjects, excludedProjects, resumeFrom, makeBehavior, expectedReactorProjects description, selectedProjects, excludedProjects, resumeFrom, makeBehavior, asList( expectedReactorProjects ), requestedPom
}; };
} }
} }

View File

@ -24,7 +24,10 @@ import org.codehaus.plexus.logging.Logger;
/** /**
* @author jdcasey * @author jdcasey
*
* @deprecated Use SLF4J directly
*/ */
@Deprecated
public class DefaultLog public class DefaultLog
implements Log implements Log
{ {

View File

@ -149,6 +149,10 @@ public abstract class AbstractMojo
/** Plugin container context */ /** Plugin container context */
private Map pluginContext; private Map pluginContext;
/**
* @deprecated Use SLF4J directly
*/
@Deprecated
@Override @Override
public void setLog( Log log ) public void setLog( Log log )
{ {
@ -167,7 +171,9 @@ public abstract class AbstractMojo
* method directly whenever you need the logger, it is fast enough and needs no caching. * method directly whenever you need the logger, it is fast enough and needs no caching.
* *
* @see org.apache.maven.plugin.Mojo#getLog() * @see org.apache.maven.plugin.Mojo#getLog()
* @deprecated Use SLF4J directly
*/ */
@Deprecated
@Override @Override
public Log getLog() public Log getLog()
{ {

View File

@ -54,16 +54,19 @@ public interface Mojo
* and feedback to the user. * and feedback to the user.
* *
* @param log a new logger * @param log a new logger
*
* @deprecated Use SLF4J directly
*/ */
// TODO not sure about this here, and may want a getLog on here as well/instead @Deprecated
void setLog( Log log ); void setLog( Log log );
/** /**
* Furnish access to the standard Maven logging mechanism which is managed in this base class. * Furnish access to the standard Maven logging mechanism which is managed in this base class.
* *
* @return a log4j-like logger object which allows plugins to create messages at levels of <code>"debug"</code>, * @return a log4j-like logger object which allows plugins to create messages at levels of <code>"debug"</code>,
* <code>"info"</code>, <code>"warn"</code>, and <code>"error"</code>. This logger is the accepted means to display * <code>"info"</code>, <code>"warn"</code>, and <code>"error"</code>.
* information to the user. * @deprecated Use SLF4J directly
*/ */
@Deprecated
Log getLog(); Log getLog();
} }

View File

@ -28,7 +28,10 @@ package org.apache.maven.plugin.logging;
* rather than formatting first by calling <code>toString()</code>. * rather than formatting first by calling <code>toString()</code>.
* *
* @author jdcasey * @author jdcasey
*
* @deprecated Use SLF4J directly
*/ */
@Deprecated
public interface Log public interface Log
{ {
/** /**

View File

@ -26,7 +26,10 @@ import java.io.StringWriter;
* Logger with "standard" output and error output stream. * Logger with "standard" output and error output stream.
* *
* @author jdcasey * @author jdcasey
*
* @deprecated Use SLF4J directly
*/ */
@Deprecated
public class SystemStreamLog public class SystemStreamLog
implements Log implements Log
{ {

View File

@ -20,7 +20,7 @@ under the License.
<model xmlns="http://codehaus-plexus.github.io/MODELLO/1.4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <model xmlns="http://codehaus-plexus.github.io/MODELLO/1.4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://codehaus-plexus.github.io/MODELLO/1.4.0 http://codehaus-plexus.github.io/modello/xsd/modello-1.4.0.xsd" xsi:schemaLocation="http://codehaus-plexus.github.io/MODELLO/1.4.0 http://codehaus-plexus.github.io/modello/xsd/modello-1.4.0.xsd"
xsd.namespace="http://maven.apache.org/METADATA/${version}" xsd.namespace="http://maven.apache.org/METADATA/${version}"
xml.schemaLocation="http://maven.apache.org/xsd/metadata-${version}.xsd"> xml.schemaLocation="https://maven.apache.org/xsd/repository-metadata-${version}.xsd">
<id>repository-metadata</id> <id>repository-metadata</id>
<name>Metadata</name> <name>Metadata</name>
<description><![CDATA[ <description><![CDATA[