diff --git a/pom.xml b/pom.xml index 4fc1fcde21..3db1a192dd 100644 --- a/pom.xml +++ b/pom.xml @@ -200,6 +200,13 @@ ${wagonVersion} + + + org.apache.maven.enforcer + enforcer-api + 3.1.0 + + org.apache.maven.doxia diff --git a/src/it/it-max-dependency-updates-001/invoker.properties b/src/it/it-max-dependency-updates-001/invoker.properties new file mode 100644 index 0000000000..38b185e579 --- /dev/null +++ b/src/it/it-max-dependency-updates-001/invoker.properties @@ -0,0 +1,2 @@ +invoker.goals = enforcer:enforce +invoker.buildResult = failure diff --git a/src/it/it-max-dependency-updates-001/pom.xml b/src/it/it-max-dependency-updates-001/pom.xml new file mode 100644 index 0000000000..feded7f7a8 --- /dev/null +++ b/src/it/it-max-dependency-updates-001/pom.xml @@ -0,0 +1,44 @@ + + 4.0.0 + localhost + it-max-dependency-upgrades + 1.0 + pom + + + + localhost + dummy-api + 1.1 + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.1.0 + + enforce + + + + + 0 + + + + + + @project.groupId@ + @project.artifactId@ + @project.version@ + + + + + + + diff --git a/src/it/it-max-dependency-updates-002/invoker.properties b/src/it/it-max-dependency-updates-002/invoker.properties new file mode 100644 index 0000000000..a30e3767bb --- /dev/null +++ b/src/it/it-max-dependency-updates-002/invoker.properties @@ -0,0 +1,2 @@ +invoker.goals = enforcer:enforce +invoker.buildResult = success diff --git a/src/it/it-max-dependency-updates-002/pom.xml b/src/it/it-max-dependency-updates-002/pom.xml new file mode 100644 index 0000000000..c748a8293b --- /dev/null +++ b/src/it/it-max-dependency-updates-002/pom.xml @@ -0,0 +1,44 @@ + + 4.0.0 + localhost + it-max-dependency-upgrades + 1.0 + pom + + + + localhost + dummy-api + 1.1 + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.1.0 + + enforce + + + + + 1 + + + + + + @project.groupId@ + @project.artifactId@ + @project.version@ + + + + + + + diff --git a/src/it/it-max-dependency-updates-003/invoker.properties b/src/it/it-max-dependency-updates-003/invoker.properties new file mode 100644 index 0000000000..a30e3767bb --- /dev/null +++ b/src/it/it-max-dependency-updates-003/invoker.properties @@ -0,0 +1,2 @@ +invoker.goals = enforcer:enforce +invoker.buildResult = success diff --git a/src/it/it-max-dependency-updates-003/pom.xml b/src/it/it-max-dependency-updates-003/pom.xml new file mode 100644 index 0000000000..eb0f57f244 --- /dev/null +++ b/src/it/it-max-dependency-updates-003/pom.xml @@ -0,0 +1,47 @@ + + 4.0.0 + localhost + it-max-dependency-upgrades + 1.0 + pom + + + + localhost + dummy-api + 1.1 + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.1.0 + + enforce + + + + + 0 + + localhost:dummy-api + + + + + + + @project.groupId@ + @project.artifactId@ + @project.version@ + + + + + + + diff --git a/src/main/java/org/apache/maven/plugins/enforcer/MaxDependencyUpdates.java b/src/main/java/org/apache/maven/plugins/enforcer/MaxDependencyUpdates.java new file mode 100644 index 0000000000..9740f4d3bb --- /dev/null +++ b/src/main/java/org/apache/maven/plugins/enforcer/MaxDependencyUpdates.java @@ -0,0 +1,323 @@ +package org.apache.maven.plugins.enforcer; +/* + * 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.util.Arrays; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Collectors; + +import org.apache.maven.artifact.manager.WagonManager; +import org.apache.maven.artifact.metadata.ArtifactMetadataRetrievalException; +import org.apache.maven.artifact.metadata.ArtifactMetadataSource; +import org.apache.maven.artifact.repository.ArtifactRepository; +import org.apache.maven.artifact.resolver.ArtifactResolver; +import org.apache.maven.artifact.versioning.ArtifactVersion; +import org.apache.maven.enforcer.rule.api.EnforcerRule; +import org.apache.maven.enforcer.rule.api.EnforcerRuleException; +import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; +import org.apache.maven.execution.MavenSession; +import org.apache.maven.model.Dependency; +import org.apache.maven.plugin.MojoExecution; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.project.MavenProject; +import org.apache.maven.repository.RepositorySystem; +import org.apache.maven.settings.Settings; +import org.codehaus.mojo.versions.api.ArtifactVersions; +import org.codehaus.mojo.versions.api.DefaultVersionsHelper; +import org.codehaus.mojo.versions.api.VersionsHelper; +import org.codehaus.mojo.versions.utils.DependencyComparator; +import org.codehaus.mojo.versions.utils.MavenProjectUtils; +import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; +import org.codehaus.plexus.component.repository.exception.ComponentLookupException; + +import static java.util.Collections.emptyList; +import static java.util.Collections.singletonList; +import static org.codehaus.mojo.versions.filtering.DependencyFilter.filterDependencies; +import static org.codehaus.mojo.versions.filtering.WildcardMatcher.WILDCARD; +import static org.codehaus.mojo.versions.utils.MavenProjectUtils.extractDependenciesFromDependencyManagement; +import static org.codehaus.mojo.versions.utils.MavenProjectUtils.extractDependenciesFromPlugins; +import static org.codehaus.mojo.versions.utils.MavenProjectUtils.extractPluginDependenciesFromPluginsInPluginManagement; + +public class MaxDependencyUpdates implements EnforcerRule +{ + /** + * Maximum allowed number of updates. + * + * @since 2.14.0 + */ + protected int maxUpdates = 0; + + /** + * Whether to process the dependencies section of the project. + * + * @since 2.14.0 + */ + protected boolean processDependencies = true; + + /** + * Whether to process the dependencyManagement section of the project. + * + * @since 1.2 + */ + protected boolean processDependencyManagement = true; + + /** + * Whether to process the dependencyManagement part transitive or not. + * In case of type {@code pom} and scope {@code import}, this means + * by default to report also the imported dependencies. + * If the parameter is set to {@code false}, the report will only show + * updates of the imported pom itself. + * + * @since 2.14.0 + */ + protected boolean processDependencyManagementTransitive = true; + + /** + * Whether to process the dependencies sections of plugins. + * + * @since 2.14.0 + */ + protected boolean processPluginDependencies = true; + + /** + * Whether to process the dependencies sections of plugins which are defined in pluginManagement. + * + * @since 2.14.0 + */ + protected boolean processPluginDependenciesInPluginManagement = true; + + /** + * List of dependency inclusion patterns. + * Only dependencies matching all the patterns will be considered. + * The wildcard "*" can be used as the only, first, last or both characters in each token. + * The version token does support version ranges. + * + * @since 2.14.0 + */ + protected List dependencyIncludes = singletonList( WILDCARD ); + + /** + * List of dependency exclusion patterns. + * Only dependencies matching none of the patterns will be considered. + * The wildcard "*" can be used as the only, first, last or both characters in each token. + * The version token does support version ranges. + * + * @since 2.14.0 + */ + protected List dependencyExcludes = emptyList(); + + /** + * List of dependency management inclusion patterns. + * Only dependencies matching all the patterns will be considered. + * The wildcard "*" can be used as the only, first, last or both characters in each token. + * The version token does support version ranges. + * + * @since 2.14.0 + */ + protected List dependencyManagementIncludes = singletonList( WILDCARD ); + + /** + * List of dependency management exclusion patterns. + * Only dependencies matching none of the patterns will be considered. + * The wildcard "*" can be used as the only, first, last or both characters in each token. + * The version token does support version ranges. + * + * @since 2.14.0 + */ + protected List dependencyManagementExcludes = emptyList(); + + /** + * List of plugin dependency inclusion patterns. + * Only dependencies matching all the patterns will be considered. + * The wildcard "*" can be used as the only, first, last or both characters in each token. + * The version token does support version ranges. + * + * @since 2.14.0 + */ + protected List pluginDependencyIncludes = singletonList( WILDCARD ); + + /** + * List of plugin dependency exclusion patterns. + * Only dependencies matching none of the patterns will be considered. + * The wildcard "*" can be used as the only, first, last or both characters in each token. + * The version token does support version ranges. + * + * @since 2.14.0 + */ + protected List pluginDependencyExcludes = emptyList(); + + /** + * List of plugin management dependency inclusion patterns. + * Only dependencies matching all the patterns will be considered. + * The wildcard "*" can be used as the only, first, last or both characters in each token. + * The version token does support version ranges. + * + * @since 2.14.0 + */ + protected List pluginManagementDependencyIncludes = singletonList( WILDCARD ); + + /** + * List of plugin dependency management exclusion patterns. + * Only dependencies matching none of the patterns will be considered. + * The wildcard "*" can be used as the only, first, last or both characters in each token. + * The version token does support version ranges. + * + * @since 2.12.0 + */ + protected List pluginManagementDependencyExcludes = emptyList(); + + /** + * Retrieves the maven project from metadata + * @param ruleHelper EnforcerRuleHelper object + * @return maven project + */ + private static MavenProject getMavenProject( EnforcerRuleHelper ruleHelper ) + { + try + { + return (MavenProject) ruleHelper.evaluate( "${project}" ); + } + catch ( ExpressionEvaluationException e ) + { + throw new RuntimeException( "Cannot evaluate project metadata", e ); + } + } + + /** + * Creates the VersionsHelper object + * @param ruleHelper EnforcerRuleHelper object + * @return VersionsHelper object + */ + @SuppressWarnings( "unchecked" ) + private static VersionsHelper createVersionsHelper( EnforcerRuleHelper ruleHelper ) + { + try + { + return new DefaultVersionsHelper.Builder() + .withRepositorySystem( ruleHelper.getComponent( RepositorySystem.class ) ) + .withArtifactResolver( ruleHelper.getComponent( ArtifactResolver.class ) ) + .withArtifactMetadataSource( ruleHelper.getComponent( ArtifactMetadataSource.class ) ) + .withRemoteArtifactRepositories( (List) + ruleHelper.evaluate( "${project.remoteArtifactRepositories}" ) ) + .withRemotePluginRepositories( (List) + ruleHelper.evaluate( "${project.remotePluginRepositories}" ) ) + .withLocalRepository( (ArtifactRepository) ruleHelper.evaluate( "${localRepository}" ) ) + .withWagonManager( ruleHelper.getComponent( WagonManager.class ) ) + .withSettings( (Settings) ruleHelper.evaluate( "${settings}" ) ) + .withServerId( (String) ruleHelper.evaluate( "${maven.version.rules.serverId}" ) ) + .withRulesUri( null ) + .withRuleSet( null ) + .withIgnoredVersions( null ) + .withLog( ruleHelper.getLog() ) + .withMavenSession( (MavenSession) ruleHelper.evaluate( "${session}" ) ) + .withMojoExecution( (MojoExecution) ruleHelper.evaluate( "${mojoExecution}" ) ) + .build(); + } + catch ( ExpressionEvaluationException e ) + { + throw new RuntimeException( "Cannot evaluate project metadata", e ); + } + catch ( ComponentLookupException | MojoExecutionException e ) + { + throw new RuntimeException( "Cannot resolve dependency", e ); + } + } + @Override + public boolean isCacheable() + { + return false; + } + + @Override + public boolean isResultValid( EnforcerRule enforcerRule ) + { + return false; + } + + @Override + public String getCacheId() + { + return "Does not matter as not cacheable"; + } + + @Override + public void execute( EnforcerRuleHelper ruleHelper ) throws EnforcerRuleException + { + VersionsHelper versionsHelper = createVersionsHelper( ruleHelper ); + MavenProject project = getMavenProject( ruleHelper ); + Set dependencies = new TreeSet<>( DependencyComparator.INSTANCE ); + if ( processDependencyManagement ) + { + try + { + dependencies.addAll( filterDependencies( extractDependenciesFromDependencyManagement( project, + processDependencyManagementTransitive, ruleHelper.getLog() ), + dependencyManagementIncludes, dependencyManagementExcludes, "Dependency Management", + ruleHelper.getLog() ) ); + } + catch ( MavenProjectUtils.VersionRetrievalException e ) + { + throw new EnforcerRuleException( e.getMessage() ); + } + } + if ( processPluginDependencies ) + { + dependencies.addAll( filterDependencies( extractDependenciesFromPlugins( project ), + pluginDependencyIncludes, pluginDependencyExcludes, + "Plugin Dependencies", ruleHelper.getLog() ) ); + } + if ( processPluginDependenciesInPluginManagement ) + { + dependencies.addAll( filterDependencies( + extractPluginDependenciesFromPluginsInPluginManagement( project ), + pluginManagementDependencyIncludes, pluginManagementDependencyExcludes, + "Plugin Management Dependencies", ruleHelper.getLog() ) ); + } + if ( processDependencies ) + { + dependencies.addAll( filterDependencies( project.getDependencies(), + dependencyIncludes, dependencyExcludes, "Dependencies", ruleHelper.getLog() ) ); + } + try + { + List upgradable = versionsHelper + .lookupDependenciesUpdates( dependencies, false ) + .values() + .parallelStream() + .filter( v -> v.getVersions().length > 0 ) + .collect( Collectors.toList() ); + if ( upgradable.size() > maxUpdates ) + { + throw new EnforcerRuleException( "More than " + maxUpdates + " upgradable artifacts detected: " + + upgradable.stream().map( av -> av.getArtifact() + " -> [" + + Arrays.stream( av.getVersions() ) + .map( ArtifactVersion::toString ) + .collect( Collectors.joining( ", " ) ) + + "]" ) + .collect( Collectors.joining( ", " ) ) ); + } + } + catch ( ArtifactMetadataRetrievalException e ) + { + throw new RuntimeException( e ); + } + } +} diff --git a/src/main/java/org/codehaus/mojo/versions/DisplayDependencyUpdatesMojo.java b/src/main/java/org/codehaus/mojo/versions/DisplayDependencyUpdatesMojo.java index fa246271b1..dfdf9c2e02 100644 --- a/src/main/java/org/codehaus/mojo/versions/DisplayDependencyUpdatesMojo.java +++ b/src/main/java/org/codehaus/mojo/versions/DisplayDependencyUpdatesMojo.java @@ -29,7 +29,6 @@ import java.util.Optional; import java.util.Set; import java.util.TreeSet; -import java.util.stream.Collectors; import org.apache.maven.artifact.ArtifactUtils; import org.apache.maven.artifact.manager.WagonManager; @@ -37,30 +36,31 @@ import org.apache.maven.artifact.metadata.ArtifactMetadataSource; import org.apache.maven.artifact.resolver.ArtifactResolver; import org.apache.maven.artifact.versioning.ArtifactVersion; -import org.apache.maven.model.Build; import org.apache.maven.model.Dependency; -import org.apache.maven.model.DependencyManagement; -import org.apache.maven.model.Plugin; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; -import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectBuilder; import org.apache.maven.repository.RepositorySystem; import org.codehaus.mojo.versions.api.ArtifactVersions; import org.codehaus.mojo.versions.api.Segment; -import org.codehaus.mojo.versions.filtering.DependencyFilter; import org.codehaus.mojo.versions.filtering.WildcardMatcher; import org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader; import org.codehaus.mojo.versions.utils.DependencyComparator; +import org.codehaus.mojo.versions.utils.MavenProjectUtils; import org.codehaus.mojo.versions.utils.SegmentUtils; import org.codehaus.plexus.util.StringUtils; +import static java.util.Collections.emptySet; import static java.util.Optional.empty; import static java.util.Optional.of; import static org.apache.commons.lang3.StringUtils.countMatches; import static org.codehaus.mojo.versions.api.Segment.MAJOR; +import static org.codehaus.mojo.versions.filtering.DependencyFilter.filterDependencies; +import static org.codehaus.mojo.versions.utils.MavenProjectUtils.extractDependenciesFromDependencyManagement; +import static org.codehaus.mojo.versions.utils.MavenProjectUtils.extractDependenciesFromPlugins; +import static org.codehaus.mojo.versions.utils.MavenProjectUtils.extractPluginDependenciesFromPluginsInPluginManagement; /** * Displays all dependencies that have newer versions available. @@ -356,68 +356,6 @@ public DisplayDependencyUpdatesMojo( RepositorySystem repositorySystem, super( repositorySystem, projectBuilder, artifactMetadataSource, wagonManager, artifactResolver ); } - private static Set extractPluginDependenciesFromPluginsInPluginManagement( Build build ) - { - Set result = new TreeSet<>( DependencyComparator.INSTANCE ); - if ( build.getPluginManagement() != null ) - { - for ( Plugin plugin : build.getPluginManagement().getPlugins() ) - { - if ( plugin.getDependencies() != null && !plugin.getDependencies().isEmpty() ) - { - result.addAll( plugin.getDependencies() ); - } - } - } - return result; - } - - private static Set extractDependenciesFromPlugins( List plugins ) - { - Set result = new TreeSet<>( DependencyComparator.INSTANCE ); - for ( Plugin plugin : plugins ) - { - if ( plugin.getDependencies() != null && !plugin.getDependencies().isEmpty() ) - { - result.addAll( plugin.getDependencies() ); - } - } - return result; - } - - /** - * Returns a set of dependencies where the dependencies which are defined in the dependency management section have - * been filtered out. - * - * @param dependencies The set of dependencies. - * @param dependencyManagement The set of dependencies from the dependency management section. - * @return A new set of dependencies which are from the set of dependencies but not from the set of dependency - * management dependencies. - * @since 1.0-beta-1 - */ - private static Set removeDependencyManagment( Set dependencies, - Set dependencyManagement ) - { - Set result = new TreeSet<>( DependencyComparator.INSTANCE ); - for ( Dependency dependency : dependencies ) - { - boolean matched = false; - for ( Dependency managedDependency : dependencyManagement ) - { - if ( dependenciesMatch( dependency, managedDependency ) ) - { - matched = true; - break; - } - } - if ( !matched ) - { - result.add( dependency ); - } - } - return result; - } - // open for tests protected static boolean dependenciesMatch( Dependency dependency, Dependency managedDependency ) { @@ -491,108 +429,51 @@ public void execute() validateInput(); - Set dependencyManagement = new TreeSet<>( DependencyComparator.INSTANCE ); - DependencyManagement projectDependencyManagement = getProjectDependencyManagement( getProject() ); - if ( projectDependencyManagement != null ) - { - - List dependenciesFromPom = projectDependencyManagement.getDependencies(); - for ( Dependency dependency : dependenciesFromPom ) - { - getLog().debug( "dependency from pom: " + dependency.getGroupId() + ":" + dependency.getArtifactId() - + ":" + dependency.getVersion() + ":" + dependency.getScope() ); - if ( dependency.getVersion() == null ) - { - // get parent and get the information from there. - if ( getProject().hasParent() ) - { - getLog().debug( "Reading parent dependencyManagement information" ); - DependencyManagement parentProjectDependencyManagement = - getProjectDependencyManagement( getProject().getParent() ); - if ( parentProjectDependencyManagement != null ) - { - List parentDeps = parentProjectDependencyManagement.getDependencies(); - for ( Dependency parentDep : parentDeps ) - { - // only groupId && artifactId needed cause version is null - if ( dependency.getGroupId().equals( parentDep.getGroupId() ) - && dependency.getArtifactId().equals( parentDep.getArtifactId() ) - && dependency.getType().equals( parentDep.getType() ) ) - { - dependencyManagement.add( parentDep ); - } - } - } - } - else - { - String message = "We can't get the version for the dependency " + dependency.getGroupId() + ":" - + dependency.getArtifactId() + " cause there does not exist a parent."; - getLog().error( message ); - // Throw error cause we will not able to get a version for a dependency. - throw new MojoExecutionException( message ); - } - } - else - { - dependencyManagement.add( dependency ); - } - } - } - - Set dependencies = new TreeSet<>( DependencyComparator.INSTANCE ); - dependencies.addAll( getProject().getDependencies() ); - - if ( isProcessingDependencyManagement() ) - { - dependencies = removeDependencyManagment( dependencies, dependencyManagement ); - } - - Set pluginDependencies = new TreeSet<>( DependencyComparator.INSTANCE ); - - if ( isProcessingPluginDependencies() ) - { - pluginDependencies = extractDependenciesFromPlugins( getProject().getBuildPlugins() ); - } - - Set pluginDependenciesInPluginManagement = new TreeSet<>( DependencyComparator.INSTANCE ); - if ( isProcessPluginDependenciesInDependencyManagement() ) - { - pluginDependenciesInPluginManagement = - extractPluginDependenciesFromPluginsInPluginManagement( getProject().getBuild() ); - } + Set dependencyManagement = emptySet(); try { if ( isProcessingDependencyManagement() ) { - dependencyManagement = filterDependencyManagementIncludes( dependencyManagement ); + dependencyManagement = filterDependencies( extractDependenciesFromDependencyManagement( getProject(), + processDependencyManagementTransitive, getLog() ), + dependencyManagementIncludes, dependencyManagementExcludes, "Dependecy Management", + getLog() ); - logUpdates( getHelper().lookupDependenciesUpdates( dependencyManagement, false ), - "Dependency Management" ); + logUpdates( getHelper().lookupDependenciesUpdates( dependencyManagement, + false ), "Dependency Management" ); } if ( isProcessingDependencies() ) { - dependencies = filterDependencyIncludes( dependencies ); - - logUpdates( getHelper().lookupDependenciesUpdates( dependencies, false ), "Dependencies" ); + Set finalDependencyManagement = dependencyManagement; + logUpdates( getHelper().lookupDependenciesUpdates( + filterDependencies( getProject().getDependencies() + .parallelStream() + .filter( dep -> finalDependencyManagement.parallelStream() + .noneMatch( depMan -> dependenciesMatch( dep, depMan ) ) ) + .collect( () -> new TreeSet<>( DependencyComparator.INSTANCE ), Set::add, Set::addAll ), + dependencyIncludes, dependencyExcludes, "Dependencies", getLog() ), + false ), + "Dependencies" ); } if ( isProcessPluginDependenciesInDependencyManagement() ) { - pluginDependenciesInPluginManagement = - filterPluginManagementIncludes( pluginDependenciesInPluginManagement ); - - logUpdates( getHelper().lookupDependenciesUpdates( pluginDependenciesInPluginManagement, false ), - "pluginManagement of plugins" ); + logUpdates( getHelper().lookupDependenciesUpdates( filterDependencies( + extractPluginDependenciesFromPluginsInPluginManagement( getProject() ), + pluginManagementDependencyIncludes, pluginManagementDependencyExcludes, + "Plugin Management Dependencies", getLog() ), false ), + "pluginManagement of plugins" ); } if ( isProcessingPluginDependencies() ) { - pluginDependencies = filterPluginDependencyIncludes( pluginDependencies ); - - logUpdates( getHelper().lookupDependenciesUpdates( pluginDependencies, false ), "Plugin Dependencies" ); + logUpdates( getHelper().lookupDependenciesUpdates( filterDependencies( + extractDependenciesFromPlugins( getProject() ), + pluginDependencyIncludes, pluginDependencyExcludes, "Plugin Dependencies", + getLog() ), false ), + "Plugin Dependencies" ); } } - catch ( ArtifactMetadataRetrievalException e ) + catch ( ArtifactMetadataRetrievalException | MavenProjectUtils.VersionRetrievalException e ) { throw new MojoExecutionException( e.getMessage(), e ); } @@ -626,72 +507,6 @@ static void validateGAVList( List gavList, int numSections, String argum } } - private Set filterDependencyIncludes( Set dependencies ) - { - return filterDependencies( dependencies, dependencyIncludes, dependencyExcludes, "Dependencies" ); - } - - private Set filterDependencyManagementIncludes( Set dependencyManagement ) - { - return filterDependencies( dependencyManagement, - dependencyManagementIncludes, dependencyManagementExcludes, "Dependecy Management" ); - } - - private Set filterPluginDependencyIncludes( Set dependencies ) - { - return filterDependencies( dependencies, pluginDependencyIncludes, pluginDependencyExcludes, - "Plugin Dependencies" ); - } - - private Set filterPluginManagementIncludes( Set dependencyManagement ) - { - return filterDependencies( dependencyManagement, - pluginManagementDependencyIncludes, pluginManagementDependencyExcludes, - "Plugin Management Dependencies" ); - } - - private Set filterDependencies( - Set dependencies, - List includes, - List excludes, - String section - ) - { - DependencyFilter includeDeps = DependencyFilter.parseFrom( includes ); - DependencyFilter excludeDeps = DependencyFilter.parseFrom( excludes ); - - Set filtered = includeDeps.retainingIn( dependencies ); - filtered = excludeDeps.removingFrom( filtered ); - - if ( getLog().isDebugEnabled() ) - { - getLog().debug( String.format( "parsed includes in %s: %s -> %s", section, includes, includeDeps ) ); - getLog().debug( String.format( "parsed excludes in %s: %s -> %s", section, excludes, excludeDeps ) ); - getLog().debug( String.format( "Unfiltered %s: ", section ) + output( dependencies ) ); - getLog().debug( String.format( "Filtered %s: ", section ) + output( filtered ) ); - } - - return filtered; - } - - private String output( Set dependencies ) - { - return dependencies.stream() - .map( d -> String.format( "%s:%s:%s", d.getGroupId(), d.getArtifactId(), d.getVersion() ) ) - .collect( Collectors.joining( ", " ) ); - } - private DependencyManagement getProjectDependencyManagement( MavenProject project ) - { - if ( processDependencyManagementTransitive ) - { - return project.getDependencyManagement(); - } - else - { - return project.getOriginalModel().getDependencyManagement(); - } - } - private Optional calculateUpdateScope() { return allowAnyUpdates diff --git a/src/main/java/org/codehaus/mojo/versions/filtering/DependencyFilter.java b/src/main/java/org/codehaus/mojo/versions/filtering/DependencyFilter.java index 07bf61617e..6f9b2874e5 100644 --- a/src/main/java/org/codehaus/mojo/versions/filtering/DependencyFilter.java +++ b/src/main/java/org/codehaus/mojo/versions/filtering/DependencyFilter.java @@ -1,5 +1,6 @@ package org.codehaus.mojo.versions.filtering; +import java.util.Collection; import java.util.List; import java.util.Set; import java.util.TreeSet; @@ -7,6 +8,7 @@ import java.util.stream.Collectors; import org.apache.maven.model.Dependency; +import org.apache.maven.plugin.logging.Log; import org.codehaus.mojo.versions.utils.DependencyComparator; public class DependencyFilter @@ -43,12 +45,12 @@ public String toString() return String.format( "%s{%s}", getClass().getSimpleName(), pattern ); } - public Set retainingIn( Set dependencies ) + public Set retainingIn( Collection dependencies ) { return filterBy( dependencies, this::matchersMatch ); } - public Set removingFrom( Set dependencies ) + public Set removingFrom( Collection dependencies ) { return filterBy( dependencies, not( this::matchersMatch ) ); } @@ -58,10 +60,51 @@ private boolean matchersMatch( Dependency dependency ) return matchers.stream().anyMatch( m -> m.test( dependency ) ); } - private TreeSet filterBy( Set dependencies, Predicate predicate ) + private TreeSet filterBy( Collection dependencies, Predicate predicate ) { return dependencies.stream() .filter( predicate ) .collect( Collectors.toCollection( () -> new TreeSet<>( DependencyComparator.INSTANCE ) ) ); } + + /** + * Returns a set of dependencies filtered by the given include- and exclude filters. + * @param dependencies collection of dependencies to filter + * @param includes a list of dependency includes + * @param excludes a list of dependency excludes + * @param section if log is not null, dependency section name for the debug log + * @param log null or log to which debug information will be logged + * @return filtered set of dependencies + */ + public static Set filterDependencies( + Collection dependencies, + List includes, + List excludes, + String section, + Log log + ) + { + DependencyFilter includeDeps = DependencyFilter.parseFrom( includes ); + DependencyFilter excludeDeps = DependencyFilter.parseFrom( excludes ); + + Set filtered = includeDeps.retainingIn( dependencies ); + filtered = excludeDeps.removingFrom( filtered ); + + if ( log != null && log.isDebugEnabled() ) + { + log.debug( String.format( "parsed includes in %s: %s -> %s", section, includes, includeDeps ) ); + log.debug( String.format( "parsed excludes in %s: %s -> %s", section, excludes, excludeDeps ) ); + log.debug( String.format( "Unfiltered %s: ", section ) + output( dependencies ) ); + log.debug( String.format( "Filtered %s: ", section ) + output( filtered ) ); + } + + return filtered; + } + + private static String output( Collection dependencies ) + { + return dependencies.stream() + .map( d -> String.format( "%s:%s:%s", d.getGroupId(), d.getArtifactId(), d.getVersion() ) ) + .collect( Collectors.joining( ", " ) ); + } } diff --git a/src/main/java/org/codehaus/mojo/versions/utils/MavenProjectUtils.java b/src/main/java/org/codehaus/mojo/versions/utils/MavenProjectUtils.java new file mode 100644 index 0000000000..14878e721a --- /dev/null +++ b/src/main/java/org/codehaus/mojo/versions/utils/MavenProjectUtils.java @@ -0,0 +1,152 @@ +package org.codehaus.mojo.versions.utils; +/* + * 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.util.List; +import java.util.Set; +import java.util.TreeSet; + +import org.apache.maven.model.Dependency; +import org.apache.maven.model.DependencyManagement; +import org.apache.maven.plugin.logging.Log; +import org.apache.maven.project.MavenProject; + +import static java.util.Collections.emptySet; + +/** + * Utility methods for extracting dependencies from a {@link org.apache.maven.project.MavenProject} + */ +public class MavenProjectUtils +{ + /** + * Retrieves dependencies from the plugins section + * @param project {@link MavenProject} instance + * @return set of {@link Dependency} objects + * or an empty set if none have been retrieveddependencies or an empty set if none have been retrieved + */ + public static Set extractPluginDependenciesFromPluginsInPluginManagement( MavenProject project ) + { + return project.getBuild() == null || project.getBuild().getPluginManagement() == null + || project.getBuild().getPluginManagement().getPlugins() == null + ? emptySet() + : project.getBuild().getPluginManagement().getPlugins().parallelStream() + .filter( plugin -> plugin.getDependencies() != null ) + .flatMap( plugin -> plugin.getDependencies().stream() ) + .collect( () -> new TreeSet<>( DependencyComparator.INSTANCE ), Set::add, Set::addAll ); + } + + /** + * Retrieves dependencies from plugin management + * @param project {@link MavenProject} instance + * @return set of {@link Dependency} objects + * or an empty set if none have been retrieveddependencies or an empty set if none have been retrieved + */ + public static Set extractDependenciesFromPlugins( MavenProject project ) + { + return project.getBuildPlugins().parallelStream() + .filter( plugin -> plugin.getDependencies() != null ) + .flatMap( plugin -> plugin.getDependencies().stream() ) + .collect( () -> new TreeSet<>( DependencyComparator.INSTANCE ), Set::add, Set::addAll ); + } + + /** + * Retrieves dependencies from the dependency management of the project + * as well as its immediate parent project. + * + * @param project {@link MavenProject} instance + * @param processDependencyManagementTransitive if {@code true}, the original model will be considered + * instead of the interpolated model, which does not contain + * imported dependencies + * @return set of {@link Dependency} objects + * or an empty set if none have been retrieveddependencies or an empty set if none have been retrieved + */ + public static Set extractDependenciesFromDependencyManagement( MavenProject project, + boolean processDependencyManagementTransitive, Log log ) + throws VersionRetrievalException + { + Set dependencyManagement = new TreeSet<>( DependencyComparator.INSTANCE ); + DependencyManagement projectDependencyManagement = processDependencyManagementTransitive + ? project.getDependencyManagement() + : project.getOriginalModel().getDependencyManagement(); + if ( projectDependencyManagement != null ) + { + + List dependenciesFromPom = projectDependencyManagement.getDependencies(); + for ( Dependency dependency : dependenciesFromPom ) + { + log.debug( "dependency from pom: " + dependency.getGroupId() + ":" + dependency.getArtifactId() + + ":" + dependency.getVersion() + ":" + dependency.getScope() ); + if ( dependency.getVersion() == null ) + { + // get parent and get the information from there. + if ( project.hasParent() ) + { + log.debug( "Reading parent dependencyManagement information" ); + DependencyManagement parentProjectDependencyManagement = + processDependencyManagementTransitive + ? project.getParent().getDependencyManagement() + : project.getParent().getOriginalModel().getDependencyManagement(); + if ( parentProjectDependencyManagement != null ) + { + List parentDeps = parentProjectDependencyManagement.getDependencies(); + for ( Dependency parentDep : parentDeps ) + { + // only groupId && artifactId needed cause version is null + if ( dependency.getGroupId().equals( parentDep.getGroupId() ) + && dependency.getArtifactId().equals( parentDep.getArtifactId() ) + && dependency.getType().equals( parentDep.getType() ) ) + { + dependencyManagement.add( parentDep ); + } + } + } + } + else + { + String message = "We can't get the version for the dependency " + dependency.getGroupId() + ":" + + dependency.getArtifactId() + " because there does not exist a parent."; + log.error( message ); + // Throw error because we will not able to get a version for a dependency. + throw new VersionRetrievalException( message ); + } + } + else + { + dependencyManagement.add( dependency ); + } + } + } + return dependencyManagement; + } + + /** + * Exception thrown if a version of a dependency cannot be found + */ + public static class VersionRetrievalException extends Exception + { + /** + * Creates a new instance of the exception object with the given message + * @param message exception message + */ + public VersionRetrievalException( String message ) + { + super( message ); + } + } +} diff --git a/src/site/markdown/enforcer/max-dependency-updates.md.vm b/src/site/markdown/enforcer/max-dependency-updates.md.vm new file mode 100644 index 0000000000..3ab0b6d37b --- /dev/null +++ b/src/site/markdown/enforcer/max-dependency-updates.md.vm @@ -0,0 +1,83 @@ +title: Introduction +author: Andrzej Jarmoniuk +date: 2022-10-27 + + + +# Max Dependency Updates + +This Maven Enforcer rule checks if the number of dependency updates does not exceed the given threshold. + +The following parameters are supported by this rule: + +| Parameter | Default | Description | +|-----------------------------------------------|:-------:|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `maxUpdates` | `0` | The total maximum allowed number of dependency updates. | +| `processDependencies` | `true` | Whether to process the dependencies section of the project. | +| `processDependencyManagement` | `true` | Whether to process the dependencyManagement section of the project. | +| `processDependencyManagementTransitive` | `true` | Whether to process the dependencyManagement part transitive or not. In case of *type* `pom` and *scope* `import`, this means by default to report also the imported dependencies. If the parameter is set to false the report will only show updates of the imported pom itself. | +| `processPluginDependencies` | `true` | Whether to process the dependencies sections of plugins. | +| `processPluginDependenciesInPluginManagement` | `true` | Whether to process the dependencies sections of plugins which are defined in pluginManagement. | +| `dependencyIncludes` | `*` | List of dependency inclusion patterns. Only dependencies matching all the patterns will be considered. The wildcard `*` can be used as the only, first, last or both characters in each token. The version token does support version ranges. | +| `dependencyExcludes` | (empty) | List of dependency exclusion patterns. Only dependencies matching none of the patterns will be considered. The wildcard `*` can be used as the only, first, last or both characters in each token. The version token does support version ranges. | +| `dependencyManagementIncludes` | `*` | List of dependency management inclusion patterns. Only dependencies matching all the patterns will be considered. The wildcard `*` can be used as the only, first, last or both characters in each token. The version token does support version ranges. | +| `dependencyManagementExcludes` | (empty) | List of dependency management exclusion patterns. Only dependencies matching none of the patterns will be considered. The wildcard `*` can be used as the only, first, last or both characters in each token. The version token does support version ranges. | +| `pluginDependencyIncludes` | `*` | List of plugin dependency inclusion patterns. Only dependencies matching all the patterns will be considered. The wildcard `*` can be used as the only, first, last or both characters in each token. The version token does support version ranges. | +| `pluginDependencyExcludes` | (empty) | List of plugin dependency exclusion patterns. Only dependencies matching none of the patterns will be considered. The wildcard `*` can be used as the only, first, last or both characters in each token. The version token does support version ranges. | +| `pluginManagementDependencyIncludes` | `*` | List of plugin management dependency inclusion patterns. Only dependencies matching all the patterns will be considered. The wildcard `*` can be used as the only, first, last or both characters in each token. The version token does support version ranges. | +| `pluginManagementDependencyExcludes` | (empty) | List of plugin management dependency exclusion patterns. Only dependencies matching none of the patterns will be considered. The wildcard `*` can be used as the only, first, last or both characters in each token. The version token does support version ranges. | + +Sample Plugin Configuration: + +```xml + +... + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.1.0 + + enforce + + + + + 0 + + localhost:dummy-api + + + + + + + ${project.groupId} + ${project.artifactId} + ${project.version} + + + + + + + +``` \ No newline at end of file diff --git a/src/site/markdown/index.md b/src/site/markdown/index.md index cf780e9359..2d29145e99 100644 --- a/src/site/markdown/index.md +++ b/src/site/markdown/index.md @@ -87,6 +87,12 @@ The Versions Plugin has the following reporting goals. * [versions:parent-updates-report](./parent-updates-report-mojo.html) produces a report on possible parent artifact upgrades. +## Enforcer rules overview + +The Versions Plugin currently provides one Maven Enforcer Plugin rule: +* [maxDependencyUpdates](./enforcer/max-dependency-updates.html) allows the user to specify a maximum number of updates which, + if exceeded, will trigger the enforcer plugin to fail. + ## Usage General instructions on how to use the Versions Plugin can be found on the [usage page](./usage.html). Some more diff --git a/src/test/java/org/apache/maven/plugins/enforcer/MaxDependencyUpdatesTest.java b/src/test/java/org/apache/maven/plugins/enforcer/MaxDependencyUpdatesTest.java new file mode 100644 index 0000000000..90f9597120 --- /dev/null +++ b/src/test/java/org/apache/maven/plugins/enforcer/MaxDependencyUpdatesTest.java @@ -0,0 +1,238 @@ +package org.apache.maven.plugins.enforcer; +/* + * 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.util.Arrays; +import java.util.HashMap; + +import org.apache.maven.artifact.metadata.ArtifactMetadataSource; +import org.apache.maven.artifact.resolver.ArtifactResolver; +import org.apache.maven.enforcer.rule.api.EnforcerRuleException; +import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; +import org.apache.maven.execution.MavenSession; +import org.apache.maven.plugin.MojoExecution; +import org.apache.maven.plugin.testing.stubs.StubArtifactRepository; +import org.apache.maven.project.MavenProject; +import org.apache.maven.repository.RepositorySystem; +import org.apache.maven.settings.Settings; +import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; +import org.codehaus.plexus.component.repository.exception.ComponentLookupException; +import org.junit.Test; +import org.mockito.ArgumentMatchers; + +import static java.util.Collections.singletonList; +import static org.codehaus.mojo.versions.utils.DependencyBuilder.dependencyWith; +import static org.codehaus.mojo.versions.utils.MockUtils.mockArtifactMetadataSource; +import static org.codehaus.mojo.versions.utils.MockUtils.mockRepositorySystem; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class MaxDependencyUpdatesTest +{ + private static Settings createSettings() + { + return new Settings(); + } + + private static MavenSession createSession() + { + return mock( MavenSession.class ); + } + + private static MojoExecution createMojoExecution() + { + return mock( MojoExecution.class ); + } + + + private static EnforcerRuleHelper mockRuleHelper( MavenProject mavenProject, + ArtifactMetadataSource artifactMetadataSource ) + throws ExpressionEvaluationException, ComponentLookupException + { + EnforcerRuleHelper ruleHelper = mock( EnforcerRuleHelper.class ); + when( ruleHelper.evaluate( anyString() ) ) + .then( ( a ) -> "${project}".equals( a.getArgument( 0 ) ) + ? mavenProject + : "${localRepository}".equals( a.getArgument( 0 ) ) + ? new StubArtifactRepository( "" ) + : "${settings}".equals( a.getArgument( 0 ) ) + ? createSettings() + : "${session}".equals( a.getArgument( 0 ) ) + ? createSession() + : "${mojoExecution}".equals( a.getArgument( 0 ) ) + ? createMojoExecution() + : null ); + when( ruleHelper.getComponent( ArgumentMatchers.>any() ) ) + .then( ( a ) -> a.getArgument( 0 ) == RepositorySystem.class + ? mockRepositorySystem() + : a.getArgument( 0 ) == ArtifactResolver.class + ? mock( ArtifactResolver.class ) + : a.getArgument( 0 ) == ArtifactMetadataSource.class + ? artifactMetadataSource + : null ); + return ruleHelper; + } + + @Test + public void testRuleFailsByMaxUpdatesExceeded() + throws ExpressionEvaluationException, ComponentLookupException + { + EnforcerRuleHelper ruleHelper = mockRuleHelper( new MavenProject() + {{ + setDependencies( Arrays.asList( + dependencyWith( "group", "artifactA", "1.0.0" ), + dependencyWith( "group", "artifactB", "1.0.0" ) ) ); + }}, mockArtifactMetadataSource( new HashMap() + {{ + put( "artifactA", new String[] { "1.0.0", "2.0.0" } ); + put( "artifactB", new String[] { "1.0.0", "2.0.0" } ); + }} ) ); + + try + { + new MaxDependencyUpdates() + {{ + maxUpdates = 1; + }}.execute( ruleHelper ); + + fail( "EnforcerRuleException should have been thrown" ); + } + catch ( EnforcerRuleException e ) + { + assertThat( e.getMessage(), containsString( "More than 1 upgradable artifacts detected" ) ); + } + } + + @Test + public void testRulePassesByMaxUpdatesNotExceeded() + throws ExpressionEvaluationException, ComponentLookupException + { + EnforcerRuleHelper ruleHelper = mockRuleHelper( new MavenProject() + {{ + setDependencies( singletonList( + dependencyWith( "group", "artifactA", "1.0.0" ) ) ); + }}, mockArtifactMetadataSource( new HashMap() + {{ + put( "artifactA", new String[] { "1.0.0", "2.0.0" } ); + }} ) ); + + try + { + new MaxDependencyUpdates() + {{ + maxUpdates = 1; + }}.execute( ruleHelper ); + } + catch ( EnforcerRuleException e ) + { + fail( "No EnforcerRuleException should have been thrown" ); + } + } + + @Test + public void testRulePassesByMaxUpdatesNotExceededDependencyIncludes() + throws ExpressionEvaluationException, ComponentLookupException + { + EnforcerRuleHelper ruleHelper = mockRuleHelper( new MavenProject() + {{ + setDependencies( Arrays.asList( + dependencyWith( "group", "artifactA", "1.0.0" ), + dependencyWith( "group", "artifactB", "1.0.0" ) ) ); + }}, mockArtifactMetadataSource( new HashMap() + {{ + put( "artifactA", new String[] { "1.0.0", "2.0.0" } ); + put( "artifactB", new String[] { "1.0.0" } ); + }} ) ); + + try + { + new MaxDependencyUpdates() + {{ + dependencyIncludes = singletonList( "group:artifactB" ); + }}.execute( ruleHelper ); + } + catch ( EnforcerRuleException e ) + { + fail( "No EnforcerRuleException should have been thrown" ); + } + } + + @Test + public void testRulePassesByMaxUpdatesNotExceededDependencyExcludes() + throws ExpressionEvaluationException, ComponentLookupException + { + EnforcerRuleHelper ruleHelper = mockRuleHelper( new MavenProject() + {{ + setDependencies( Arrays.asList( + dependencyWith( "group", "artifactA", "1.0.0" ), + dependencyWith( "group", "artifactB", "1.0.0" ) ) ); + }}, mockArtifactMetadataSource( new HashMap() + {{ + put( "artifactA", new String[] { "1.0.0", "2.0.0" } ); + put( "artifactB", new String[] { "1.0.0" } ); + }} ) ); + + try + { + new MaxDependencyUpdates() + {{ + dependencyExcludes = singletonList( "group:artifactA" ); + }}.execute( ruleHelper ); + } + catch ( EnforcerRuleException e ) + { + fail( "No EnforcerRuleException should have been thrown" ); + } + } + + @Test + public void testRulePassesByMaxUpdatesNotExceededDependencyIncludesExcludes() + throws ExpressionEvaluationException, ComponentLookupException + { + EnforcerRuleHelper ruleHelper = mockRuleHelper( new MavenProject() + {{ + setDependencies( Arrays.asList( + dependencyWith( "group", "artifactA", "1.0.0" ), + dependencyWith( "group", "artifactB", "1.0.0" ) ) ); + }}, mockArtifactMetadataSource( new HashMap() + {{ + put( "artifactA", new String[] { "1.0.0", "2.0.0" } ); + put( "artifactB", new String[] { "1.0.0" } ); + }} ) ); + + try + { + new MaxDependencyUpdates() + {{ + dependencyIncludes = singletonList( "group:*" ); + dependencyExcludes = singletonList( "group:artifactA" ); + }}.execute( ruleHelper ); + } + catch ( EnforcerRuleException e ) + { + fail( "No EnforcerRuleException should have been thrown" ); + } + } + + +} diff --git a/src/test/resources/org/codehaus/mojo/max-dependency-upgrades/pom.xml b/src/test/resources/org/codehaus/mojo/max-dependency-upgrades/pom.xml new file mode 100644 index 0000000000..c869d723f4 --- /dev/null +++ b/src/test/resources/org/codehaus/mojo/max-dependency-upgrades/pom.xml @@ -0,0 +1,44 @@ + + 4.0.0 + default-group + default-artifact + 1.0 + pom + + + + default-group + artifactA + 1.0.0 + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.1.0 + + enforce + + + + + 0 + + + true + + + + org.codehaus.mojo + versions-maven-plugin + ${project.version} + + + + + +