From a4b99bfcec4252648c9cac13aff14e7ef5a05947 Mon Sep 17 00:00:00 2001 From: Andrzej Jarmoniuk Date: Sun, 27 Nov 2022 10:44:36 +0100 Subject: [PATCH] #704: Removing ArtifactRepository leftovers; using ranges for version resolution --- versions-common/pom.xml | 14 +- .../versions/api/DefaultVersionsHelper.java | 24 +- .../codehaus/mojo/versions/api/PomHelper.java | 28 - .../mojo/versions/api/VersionsHelper.java | 17 + versions-enforcer/pom.xml | 7 - .../enforcer/MaxDependencyUpdatesTest.java | 25 +- versions-maven-plugin/pom.xml | 13 +- .../mojo/versions/AbstractVersionsReport.java | 34 - .../versions/AbstractVersionsUpdaterMojo.java | 3 +- .../versions/DisplayPluginUpdatesMojo.java | 814 ++++-------------- .../codehaus/mojo/versions/RevertMojo.java | 4 - .../PropertyUpdatesReportMojoTest.java | 4 - .../mojo/versions/UpdateParentMojoTest.java | 3 - versions-test/pom.xml | 7 +- 14 files changed, 248 insertions(+), 749 deletions(-) diff --git a/versions-common/pom.xml b/versions-common/pom.xml index 5b791a896b..280b6b9cf9 100644 --- a/versions-common/pom.xml +++ b/versions-common/pom.xml @@ -40,10 +40,9 @@ provided - org.apache.maven - maven-compat - ${mavenVersion} - provided + org.apache.maven.wagon + wagon-provider-api + 3.5.2 org.apache.maven @@ -110,6 +109,13 @@ slf4j-simple test + + + org.apache.maven + maven-compat + ${mavenVersion} + test + diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/api/DefaultVersionsHelper.java b/versions-common/src/main/java/org/codehaus/mojo/versions/api/DefaultVersionsHelper.java index 85ce4a8aef..669efd5430 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/api/DefaultVersionsHelper.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/api/DefaultVersionsHelper.java @@ -53,6 +53,7 @@ import org.apache.maven.artifact.resolver.ArtifactResolutionException; import org.apache.maven.artifact.versioning.ArtifactVersion; import org.apache.maven.artifact.versioning.DefaultArtifactVersion; +import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Dependency; import org.apache.maven.model.Plugin; @@ -175,7 +176,8 @@ public Log getLog() } @Override - public ArtifactVersions lookupArtifactVersions( Artifact artifact, boolean usePluginRepositories ) + public ArtifactVersions lookupArtifactVersions( Artifact artifact, VersionRange versionRange, + boolean usePluginRepositories ) throws VersionRetrievalException { try @@ -189,11 +191,14 @@ public ArtifactVersions lookupArtifactVersions( Artifact artifact, boolean usePl return new ArtifactVersions( artifact, aetherRepositorySystem.resolveVersionRange( mavenSession.getRepositorySession(), new VersionRangeRequest( - toArtifact( artifact ).setVersion( "(,)" ), - usePluginRepositories - ? mavenSession.getCurrentProject().getRemotePluginRepositories() - : mavenSession.getCurrentProject().getRemoteProjectRepositories(), - "lookupArtifactVersions" ) ) + toArtifact( artifact ).setVersion( + versionRange != null + ? versionRange.toString() + : "(,)" ), + usePluginRepositories + ? mavenSession.getCurrentProject().getRemotePluginRepositories() + : mavenSession.getCurrentProject().getRemoteProjectRepositories(), + "lookupArtifactVersions" ) ) .getVersions() .parallelStream() .filter( v -> ignoredVersions.stream() @@ -237,6 +242,13 @@ public ArtifactVersions lookupArtifactVersions( Artifact artifact, boolean usePl } } + @Override + public ArtifactVersions lookupArtifactVersions( Artifact artifact, boolean usePluginRepositories ) + throws VersionRetrievalException + { + return lookupArtifactVersions( artifact, null, usePluginRepositories ); + } + /** * Returns a list of versions which should not be considered when looking for updates. * diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/api/PomHelper.java b/versions-common/src/main/java/org/codehaus/mojo/versions/api/PomHelper.java index f0fbd59472..cc1d1126c1 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/api/PomHelper.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/api/PomHelper.java @@ -37,7 +37,6 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import java.util.Objects; import java.util.Properties; import java.util.Set; import java.util.Stack; @@ -57,7 +56,6 @@ import org.apache.maven.model.Profile; import org.apache.maven.model.ReportPlugin; import org.apache.maven.model.building.ModelBuildingRequest; -import org.apache.maven.model.building.UrlModelSource; import org.apache.maven.model.io.xpp3.MavenXpp3Reader; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.DefaultProjectBuildingRequest; @@ -1523,32 +1521,6 @@ public static MavenProject getLocalRoot( ProjectBuilder projectBuilder, } } - /** - * Retrieves the standalone superproject - * - * @param projectBuilder {@link ProjectBuilder} instance - * @param mavenSession {@link MavenSession} instance - * @param logger The logger to log tog - * - * @return superproject retrieved - * @throws ProjectBuildingException if the retrieval fails - */ - public static MavenProject getStandaloneSuperProject( ProjectBuilder projectBuilder, - MavenSession mavenSession, - Log logger ) throws ProjectBuildingException - { - ProjectBuildingResult result = projectBuilder.build( new UrlModelSource( - Objects.requireNonNull( PomHelper.class.getResource( "standalone.xml" ) ) ), - createProjectBuilderRequest( mavenSession, r -> r.setProcessPlugins( false ) ) ); - if ( !result.getProblems().isEmpty() ) - { - logger.warn( "Problems encountered during building of the superproject." ); - result.getProblems().forEach( p -> - logger.warn( "\t" + p.getMessage() ) ); - } - return result.getProject(); - } - /** *

Convenience method for creating a {@link ProjectBuildingRequest} instance based on maven session.

*

Note: The method initializes the remote repositories with the remote artifact repositories. diff --git a/versions-common/src/main/java/org/codehaus/mojo/versions/api/VersionsHelper.java b/versions-common/src/main/java/org/codehaus/mojo/versions/api/VersionsHelper.java index 4f56849e91..8e66f93223 100644 --- a/versions-common/src/main/java/org/codehaus/mojo/versions/api/VersionsHelper.java +++ b/versions-common/src/main/java/org/codehaus/mojo/versions/api/VersionsHelper.java @@ -27,6 +27,7 @@ import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.resolver.ArtifactResolutionException; import org.apache.maven.artifact.versioning.ArtifactVersion; +import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.model.Dependency; import org.apache.maven.model.Plugin; import org.apache.maven.plugin.MojoExecutionException; @@ -154,6 +155,22 @@ Artifact createDependencyArtifact( String groupId, String artifactId, String ver ArtifactVersions lookupArtifactVersions( Artifact artifact, boolean usePluginRepositories ) throws VersionRetrievalException; + /** + * Looks up the versions of the specified artifact that are available in either the local repository, or the + * appropriate remote repositories. + * + * @param artifact The artifact to look for versions of. + * @param versionRange versionRange to restrict the search + * @param usePluginRepositories true will consult the pluginRepositories, while false will + * consult the repositories for normal dependencies. + * @return The details of the available artifact versions. + * @throws VersionRetrievalException thrown if version resolution fails + * @since 1.0-alpha-3 + */ + ArtifactVersions lookupArtifactVersions( Artifact artifact, VersionRange versionRange, + boolean usePluginRepositories ) + throws VersionRetrievalException; + /** * Looks up the updates for a set of dependencies. * diff --git a/versions-enforcer/pom.xml b/versions-enforcer/pom.xml index a3cda5ad64..376f23b5f9 100644 --- a/versions-enforcer/pom.xml +++ b/versions-enforcer/pom.xml @@ -46,13 +46,6 @@ provided - - org.apache.maven - maven-compat - ${mavenVersion} - provided - - org.junit.jupiter junit-jupiter diff --git a/versions-enforcer/src/test/java/org/apache/maven/plugins/enforcer/MaxDependencyUpdatesTest.java b/versions-enforcer/src/test/java/org/apache/maven/plugins/enforcer/MaxDependencyUpdatesTest.java index 7493bcce74..62e029e813 100644 --- a/versions-enforcer/src/test/java/org/apache/maven/plugins/enforcer/MaxDependencyUpdatesTest.java +++ b/versions-enforcer/src/test/java/org/apache/maven/plugins/enforcer/MaxDependencyUpdatesTest.java @@ -20,14 +20,11 @@ import java.util.HashMap; -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.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; @@ -57,23 +54,17 @@ private static EnforcerRuleHelper mockRuleHelper( MavenProject mavenProject, when( ruleHelper.evaluate( anyString() ) ) .then( ( a ) -> "${project}".equals( a.getArgument( 0 ) ) ? mavenProject - : "${localRepository}".equals( a.getArgument( 0 ) ) - ? new StubArtifactRepository( "" ) - : "${settings}".equals( a.getArgument( 0 ) ) - ? new Settings() - : "${session}".equals( a.getArgument( 0 ) ) - ? mockMavenSession() - : "${mojoExecution}".equals( a.getArgument( 0 ) ) - ? mock( MojoExecution.class ) - : null ); + : "${session}".equals( a.getArgument( 0 ) ) + ? mockMavenSession() + : "${mojoExecution}".equals( a.getArgument( 0 ) ) + ? mock( MojoExecution.class ) + : 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 ) == org.eclipse.aether.RepositorySystem.class - ? aetherRepositorySystem - : null ); + : a.getArgument( 0 ) == org.eclipse.aether.RepositorySystem.class + ? aetherRepositorySystem + : null ); return ruleHelper; } diff --git a/versions-maven-plugin/pom.xml b/versions-maven-plugin/pom.xml index e586a8ba11..df877d91a1 100644 --- a/versions-maven-plugin/pom.xml +++ b/versions-maven-plugin/pom.xml @@ -58,12 +58,6 @@ ${mavenVersion} provided - - org.apache.maven - maven-compat - ${mavenVersion} - provided - org.apache.maven maven-model @@ -162,6 +156,13 @@ slf4j-simple test + + + org.apache.maven + maven-compat + ${mavenVersion} + test + diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractVersionsReport.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractVersionsReport.java index b33e642016..bf7d697965 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractVersionsReport.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractVersionsReport.java @@ -24,9 +24,6 @@ import java.util.Map; import java.util.Set; -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.versioning.ArtifactVersion; -import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.doxia.sink.Sink; import org.apache.maven.doxia.siterenderer.Renderer; import org.apache.maven.execution.MavenSession; @@ -38,9 +35,7 @@ import org.apache.maven.reporting.MavenReportException; import org.apache.maven.repository.RepositorySystem; import org.apache.maven.wagon.Wagon; -import org.codehaus.mojo.versions.api.ArtifactVersions; import org.codehaus.mojo.versions.api.DefaultVersionsHelper; -import org.codehaus.mojo.versions.api.VersionRetrievalException; import org.codehaus.mojo.versions.api.VersionsHelper; import org.codehaus.mojo.versions.model.RuleSet; import org.codehaus.mojo.versions.reporting.ReportRendererFactory; @@ -243,35 +238,6 @@ protected void executeReport( Locale locale ) protected abstract void doGenerateReport( Locale locale, Sink sink ) throws MavenReportException, MojoExecutionException; - /** - * Finds the latest version of the specified artifact that matches the version range. - * - * @param artifact The artifact. - * @param versionRange The version range. - * @param allowingSnapshots null for no override, otherwise the local override to apply. - * @param usePluginRepositories Use plugin repositories - * @return The latest version of the specified artifact that matches the specified version range or - * null if no matching version could be found. - * @throws MavenReportException If the artifact metadata could not be found. - * @since 1.0-alpha-1 - */ - protected ArtifactVersion findLatestVersion( Artifact artifact, VersionRange versionRange, - Boolean allowingSnapshots, boolean usePluginRepositories ) - throws MavenReportException - { - boolean includeSnapshots = allowingSnapshots != null ? allowingSnapshots : this.allowSnapshots; - try - { - final ArtifactVersions artifactVersions = - getHelper().lookupArtifactVersions( artifact, usePluginRepositories ); - return artifactVersions.getNewestVersion( versionRange, includeSnapshots ); - } - catch ( VersionRetrievalException e ) - { - throw new MavenReportException( e.getMessage(), e ); - } - } - @Override protected MavenProject getProject() { diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractVersionsUpdaterMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractVersionsUpdaterMojo.java index 92021ba27d..86fc57d526 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractVersionsUpdaterMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/AbstractVersionsUpdaterMojo.java @@ -308,7 +308,8 @@ protected ArtifactVersion findLatestVersion( Artifact artifact, VersionRange ver throws MojoExecutionException, VersionRetrievalException { boolean includeSnapshots = allowingSnapshots != null ? allowingSnapshots : this.allowSnapshots; - final ArtifactVersions artifactVersions = getHelper().lookupArtifactVersions( artifact, usePluginRepositories ); + final ArtifactVersions artifactVersions = getHelper().lookupArtifactVersions( artifact, versionRange, + usePluginRepositories ); return artifactVersions.getNewestVersion( versionRange, null, includeSnapshots, false ); } diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayPluginUpdatesMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayPluginUpdatesMojo.java index c38aaebbe3..3960db6e52 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayPluginUpdatesMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/DisplayPluginUpdatesMojo.java @@ -27,40 +27,29 @@ import java.io.IOException; import java.io.Reader; import java.io.StringWriter; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; import java.net.URL; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; -import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.Stack; import java.util.TreeMap; import java.util.TreeSet; import java.util.regex.Pattern; -import org.apache.maven.BuildFailureException; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.ArtifactUtils; -import org.apache.maven.artifact.repository.ArtifactRepository; -import org.apache.maven.artifact.resolver.ArtifactNotFoundException; import org.apache.maven.artifact.resolver.ArtifactResolutionException; import org.apache.maven.artifact.versioning.ArtifactVersion; import org.apache.maven.artifact.versioning.DefaultArtifactVersion; -import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.execution.RuntimeInformation; -import org.apache.maven.lifecycle.Lifecycle; -import org.apache.maven.lifecycle.LifecycleExecutionException; import org.apache.maven.lifecycle.LifecycleExecutor; -import org.apache.maven.lifecycle.mapping.LifecycleMapping; +import org.apache.maven.model.BuildBase; import org.apache.maven.model.Model; import org.apache.maven.model.Plugin; import org.apache.maven.model.Prerequisites; @@ -72,22 +61,15 @@ import org.apache.maven.model.building.ModelProblemCollectorRequest; import org.apache.maven.model.interpolation.ModelInterpolator; import org.apache.maven.model.io.xpp3.MavenXpp3Writer; -import org.apache.maven.plugin.InvalidPluginException; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugin.PluginManager; -import org.apache.maven.plugin.PluginManagerException; -import org.apache.maven.plugin.PluginNotFoundException; -import org.apache.maven.plugin.descriptor.PluginDescriptor; -import org.apache.maven.plugin.version.PluginVersionNotFoundException; -import org.apache.maven.plugin.version.PluginVersionResolutionException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.project.MavenProject; import org.apache.maven.project.ProjectBuilder; import org.apache.maven.project.ProjectBuildingException; import org.apache.maven.project.ProjectBuildingResult; import org.apache.maven.repository.RepositorySystem; -import org.apache.maven.settings.Settings; +import org.apache.maven.rtinfo.RuntimeInformation; import org.apache.maven.wagon.Wagon; import org.codehaus.mojo.versions.api.ArtifactVersions; import org.codehaus.mojo.versions.api.PomHelper; @@ -97,10 +79,13 @@ import org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader; import org.codehaus.mojo.versions.utils.DependencyBuilder; import org.codehaus.mojo.versions.utils.PluginComparator; -import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.ReaderFactory; -import org.codehaus.plexus.util.StringUtils; + +import static java.util.Collections.emptyMap; +import static java.util.Optional.ofNullable; +import static java.util.stream.Collectors.toMap; +import static java.util.stream.Collectors.toSet; /** * Displays all plugins that have newer versions available, taking care of Maven version prerequisites. @@ -110,7 +95,7 @@ */ @Mojo( name = "display-plugin-updates", threadSafe = true ) public class DisplayPluginUpdatesMojo - extends AbstractVersionsDisplayMojo + extends AbstractVersionsDisplayMojo { // ------------------------------ FIELDS ------------------------------ @@ -147,16 +132,11 @@ public class DisplayPluginUpdatesMojo private ModelInterpolator modelInterpolator; /** - * The plugin manager. + * (Injected) instance of {@link RuntimeInformation} * - * @since 1.0-alpha-1 - */ - private PluginManager pluginManager; - - /** - * @since 1.3 + * @since 2.14.0 */ - private RuntimeInformation runtimeInformation; + private final RuntimeInformation runtimeInformation; /** * The (injected) instance of {@link ProjectBuilder} @@ -175,7 +155,6 @@ public DisplayPluginUpdatesMojo( RepositorySystem repositorySystem, Map wagonMap, LifecycleExecutor lifecycleExecutor, ModelInterpolator modelInterpolator, - PluginManager pluginManager, RuntimeInformation runtimeInformation, Map changeRecorders ) { @@ -183,7 +162,6 @@ public DisplayPluginUpdatesMojo( RepositorySystem repositorySystem, this.projectBuilder = projectBuilder; this.lifecycleExecutor = lifecycleExecutor; this.modelInterpolator = modelInterpolator; - this.pluginManager = pluginManager; this.runtimeInformation = runtimeInformation; } @@ -194,123 +172,96 @@ public DisplayPluginUpdatesMojo( RepositorySystem repositorySystem, * @throws MojoExecutionException when things go wrong. */ private Map getSuperPomPluginManagement() - throws MojoExecutionException + throws MojoExecutionException { - if ( new DefaultArtifactVersion( "3.0" ).compareTo( runtimeInformation.getApplicationVersion() ) <= 0 ) + // we need to provide a copy with the version blanked out so that inferring from super-pom + // works as for 2.x as 3.x fills in the version on us! + Map result = lifecycleExecutor.getPluginsBoundByDefaultToAllLifecycles( getProject() + .getPackaging() ) + .stream() + .collect( LinkedHashMap::new, + ( m, p ) -> m.put( p.getKey(), p.getVersion() ), + Map::putAll ); + + URL superPom = getClass().getClassLoader().getResource( "org/apache/maven/model/pom-4.0.0.xml" ); + if ( superPom != null ) { - getLog().debug( "Using Maven 3.x strategy to determine superpom defined plugins" ); try { - Method getPluginsBoundByDefaultToAllLifecycles = - LifecycleExecutor.class.getMethod( "getPluginsBoundByDefaultToAllLifecycles", - String.class ); - Set plugins = - (Set) getPluginsBoundByDefaultToAllLifecycles.invoke( lifecycleExecutor, new Object[] { - getProject().getPackaging()} ); - // we need to provide a copy with the version blanked out so that inferring from super-pom - // works as for 2.x as 3.x fills in the version on us! - Map result = new LinkedHashMap<>( plugins.size() ); - for ( Plugin plugin : plugins ) - { - result.put( plugin.getKey(), plugin.getVersion() ); - } - URL superPom = getClass().getClassLoader().getResource( "org/apache/maven/model/pom-4.0.0.xml" ); - if ( superPom != null ) + try ( Reader reader = ReaderFactory.newXmlReader( superPom ) ) { - try + StringBuilder buf = new StringBuilder( IOUtil.toString( reader ) ); + ModifiedPomXMLEventReader pom = newModifiedPomXER( buf, superPom.toString() ); + + Pattern pathRegex = Pattern.compile( "/project(/profiles/profile)?" + + "((/build(/pluginManagement)?)|(/reporting))" + + "/plugins/plugin" ); + Stack pathStack = new Stack<>(); + StackState curState = null; + while ( pom.hasNext() ) { - try ( Reader reader = ReaderFactory.newXmlReader( superPom ) ) + XMLEvent event = pom.nextEvent(); + if ( event.isStartDocument() ) { - StringBuilder buf = new StringBuilder( IOUtil.toString( reader ) ); - ModifiedPomXMLEventReader pom = newModifiedPomXER( buf, superPom.toString() ); - - Pattern pathRegex = Pattern.compile( "/project(/profiles/profile)?" - + "((/build(/pluginManagement)?)|(/reporting))" - + "/plugins/plugin" ); - Stack pathStack = new Stack<>(); - StackState curState = null; - while ( pom.hasNext() ) + curState = new StackState( "" ); + pathStack.clear(); + } + else if ( event.isStartElement() ) + { + String elementName = event.asStartElement().getName().getLocalPart(); + if ( curState != null && pathRegex.matcher( curState.path ).matches() ) { - XMLEvent event = pom.nextEvent(); - if ( event.isStartDocument() ) + if ( "groupId".equals( elementName ) ) { - curState = new StackState( "" ); - pathStack.clear(); + curState.groupId = pom.getElementText().trim(); + continue; } - else if ( event.isStartElement() ) + else if ( "artifactId".equals( elementName ) ) { - String elementName = event.asStartElement().getName().getLocalPart(); - if ( curState != null && pathRegex.matcher( curState.path ).matches() ) - { - if ( "groupId".equals( elementName ) ) - { - curState.groupId = pom.getElementText().trim(); - continue; - } - else if ( "artifactId".equals( elementName ) ) - { - curState.artifactId = pom.getElementText().trim(); - continue; - - } - else if ( "version".equals( elementName ) ) - { - curState.version = pom.getElementText().trim(); - continue; - } - } + curState.artifactId = pom.getElementText().trim(); + continue; - pathStack.push( curState ); - curState = new StackState( curState.path + "/" + elementName ); } - else if ( event.isEndElement() ) + else if ( "version".equals( elementName ) ) + { + curState.version = pom.getElementText().trim(); + continue; + } + } + + pathStack.push( curState ); + curState = new StackState( curState.path + "/" + elementName ); + } + else if ( event.isEndElement() ) + { + if ( curState != null && pathRegex.matcher( curState.path ).matches() ) + { + if ( curState.artifactId != null ) { - if ( curState != null && pathRegex.matcher( curState.path ).matches() ) + Plugin plugin = new Plugin(); + plugin.setArtifactId( curState.artifactId ); + plugin.setGroupId( curState.groupId == null + ? PomHelper.APACHE_MAVEN_PLUGINS_GROUPID + : curState.groupId ); + plugin.setVersion( curState.version ); + if ( !result.containsKey( plugin.getKey() ) ) { - if ( curState.artifactId != null ) - { - Plugin plugin = new Plugin(); - plugin.setArtifactId( curState.artifactId ); - plugin.setGroupId( curState.groupId == null - ? PomHelper.APACHE_MAVEN_PLUGINS_GROUPID - : curState.groupId ); - plugin.setVersion( curState.version ); - if ( !result.containsKey( plugin.getKey() ) ) - { - result.put( plugin.getKey(), plugin.getVersion() ); - } - } + result.put( plugin.getKey(), plugin.getVersion() ); } - curState = pathStack.pop(); } } + curState = pathStack.pop(); } } - catch ( IOException | XMLStreamException e ) - { - // ignore - } } - - return result; } - catch ( NoSuchMethodException | InvocationTargetException | IllegalAccessException e1 ) + catch ( IOException | XMLStreamException e ) { - // no much we can do here + // ignore } } - getLog().debug( "Using Maven 2.x strategy to determine superpom defined plugins" ); - Map superPomPluginManagement; - try - { - superPomPluginManagement = new HashMap<>( getPluginManagement( - PomHelper.getStandaloneSuperProject( projectBuilder, session, getLog() ).getOriginalModel() ) ); - } - catch ( ProjectBuildingException e ) - { - throw new MojoExecutionException( "Could not determine the super pom.xml", e ); - } - return superPomPluginManagement; + + return result; } /** @@ -382,13 +333,16 @@ private Map getPluginManagement( Model model ) */ @SuppressWarnings( "checkstyle:MethodLength" ) public void execute() - throws MojoExecutionException, MojoFailureException + throws MojoExecutionException, MojoFailureException { logInit(); Set pluginsWithVersionsSpecified; try { - pluginsWithVersionsSpecified = findPluginsWithVersionsSpecified( getProject() ); + MavenProject project1 = getProject(); + pluginsWithVersionsSpecified = + findPluginsWithVersionsSpecified( PomHelper.readXmlFile( project1.getFile() ), + getSafeProjectPathInfo( project1 ) ); } catch ( XMLStreamException | IOException e ) { @@ -408,12 +362,12 @@ public void execute() Map parentReportPlugins = new HashMap<>(); Set plugins = getProjectPlugins( superPomPluginManagement, parentPlugins, parentBuildPlugins, - parentReportPlugins, pluginsWithVersionsSpecified ); + parentReportPlugins, pluginsWithVersionsSpecified ); List pluginUpdates = new ArrayList<>(); List pluginLockdowns = new ArrayList<>(); - ArtifactVersion curMavenVersion = runtimeInformation.getApplicationVersion(); - ArtifactVersion specMavenVersion = MinimalMavenBuildVersionFinder.find( getProject(), "2.0", getLog() ); + ArtifactVersion curMavenVersion = new DefaultArtifactVersion( runtimeInformation.getMavenVersion() ); + ArtifactVersion specMavenVersion = MinimalMavenBuildVersionFinder.find( getProject(), "3.2.5", getLog() ); ArtifactVersion minMavenVersion = null; boolean superPomDrivingMinVersion = false; // if Maven prerequisite upgraded to a version, Map @@ -442,7 +396,7 @@ public void execute() String effectiveVersion = version; Artifact artifactRange = getHelper().createPluginArtifact( plugin.getGroupId(), plugin.getArtifactId(), - version ); + version ); ArtifactVersion artifactVersion = null; try @@ -477,7 +431,7 @@ public void execute() if ( minRequires == null || compare( minRequires, pluginRequires ) > 0 ) { Map upgradePlugins = - mavenUpgrades.computeIfAbsent( pluginRequires, k -> new LinkedHashMap<>() ); + mavenUpgrades.computeIfAbsent( pluginRequires, k -> new LinkedHashMap<>() ); String upgradePluginKey = compactKey( groupId, artifactId ); if ( !upgradePlugins.containsKey( upgradePluginKey ) ) @@ -487,15 +441,15 @@ public void execute() { // plugin version configured that require a Maven version higher than spec upgradePlugins.put( upgradePluginKey, - pad( upgradePluginKey, - INFO_PAD_SIZE + getOutputLineWidthOffset(), newer ) ); + pad( upgradePluginKey, + INFO_PAD_SIZE + getOutputLineWidthOffset(), newer ) ); } else { // plugin that can be upgraded upgradePlugins.put( upgradePluginKey, pad( upgradePluginKey, INFO_PAD_SIZE - + getOutputLineWidthOffset(), - effectiveVersion, " -> ", newer ) ); + + getOutputLineWidthOffset(), + effectiveVersion, " -> ", newer ) ); } } minRequires = pluginRequires; @@ -552,15 +506,15 @@ public void execute() getLog().debug( "[" + coords + "].superPom.version=" + version ); newVersion = artifactVersion != null ? artifactVersion.toString() - : ( version != null ? version - : ( effectiveVersion != null ? effectiveVersion : "(unknown)" ) ); + : ( version != null ? version + : ( effectiveVersion != null ? effectiveVersion : "(unknown)" ) ); if ( version != null ) { superPomDrivingMinVersion = true; } pluginLockdowns.add( pad( compactKey( groupId, artifactId ), WARN_PAD_SIZE + getOutputLineWidthOffset(), - superPomDrivingMinVersion ? FROM_SUPER_POM : "", newVersion ) ); + superPomDrivingMinVersion ? FROM_SUPER_POM : "", newVersion ) ); } else if ( artifactVersion != null ) { @@ -571,11 +525,12 @@ else if ( artifactVersion != null ) newVersion = null; } if ( version != null && artifactVersion != null && newVersion != null && effectiveVersion != null - && new DefaultArtifactVersion( effectiveVersion ).compareTo( new DefaultArtifactVersion( newVersion ) ) - < 0 ) + && + new DefaultArtifactVersion( effectiveVersion ).compareTo( new DefaultArtifactVersion( newVersion ) ) + < 0 ) { pluginUpdates.add( pad( compactKey( groupId, artifactId ), INFO_PAD_SIZE + getOutputLineWidthOffset(), - effectiveVersion, " -> ", newVersion ) ); + effectiveVersion, " -> ", newVersion ) ); } } @@ -704,11 +659,12 @@ else if ( minMavenVersion != null && compare( specMavenVersion, minMavenVersion /** * Builds a {@link MavenProject} instance for the plugin with a given {@code groupId}, * {@code artifactId}, and {@code version}. - * @param groupId {@code groupId} of the plugin + * + * @param groupId {@code groupId} of the plugin * @param artifactId {@code artifactId} of the plugin - * @param version {@code version} of the plugin + * @param version {@code version} of the plugin * @return retrieved {@link MavenProject} instance for the given plugin - * @throws MojoExecutionException thrown if the artifact for the plugin could not be constructed + * @throws MojoExecutionException thrown if the artifact for the plugin could not be constructed * @throws ProjectBuildingException thrown if the {@link MavenProject} instance could not be constructed */ private MavenProject getPluginProject( String groupId, String artifactId, String version ) @@ -731,7 +687,7 @@ private MavenProject getPluginProject( String groupId, String artifactId, String if ( !result.getProblems().isEmpty() ) { getLog().warn( "Problems encountered during construction of the plugin POM for " - + probe.toString() ); + + probe.toString() ); result.getProblems().forEach( p -> getLog().warn( "\t" + p.getMessage() ) ); } @@ -762,13 +718,13 @@ private static String pad( String start, int len, String... ends ) } private Map getParentsPlugins( List parents ) - throws MojoExecutionException + throws MojoExecutionException { Map parentPlugins = new HashMap<>(); for ( MavenProject parentProject : parents ) { getLog().debug( "Processing parent: " + parentProject.getGroupId() + ":" + parentProject.getArtifactId() - + ":" + parentProject.getVersion() + " -> " + parentProject.getFile() ); + + ":" + parentProject.getVersion() + " -> " + parentProject.getFile() ); StringWriter writer = new StringWriter(); boolean havePom = false; @@ -778,8 +734,8 @@ private Map getParentsPlugins( List parents ) if ( originalModel == null ) { getLog().warn( "project.getOriginalModel()==null for " + parentProject.getGroupId() + ":" - + parentProject.getArtifactId() + ":" + parentProject.getVersion() - + " is null, substituting project.getModel()" ); + + parentProject.getArtifactId() + ":" + parentProject.getVersion() + + " is null, substituting project.getModel()" ); originalModel = parentProject.getModel(); } try @@ -795,15 +751,15 @@ private Map getParentsPlugins( List parents ) ModelBuildingRequest modelBuildingRequest = new DefaultModelBuildingRequest(); modelBuildingRequest.setUserProperties( getProject().getProperties() ); interpolatedModel = modelInterpolator.interpolateModel( originalModel, null, - modelBuildingRequest, - new IgnoringModelProblemCollector() ); + modelBuildingRequest, + new IgnoringModelProblemCollector() ); if ( havePom ) { try { Set withVersionSpecified = - findPluginsWithVersionsSpecified( new StringBuilder( writer.toString() ), - getSafeProjectPathInfo( parentProject ) ); + findPluginsWithVersionsSpecified( new StringBuilder( writer.toString() ), + getSafeProjectPathInfo( parentProject ) ); Map map = getPluginManagement( interpolatedModel ); map.keySet().retainAll( withVersionSpecified ); @@ -834,16 +790,11 @@ private Map getParentsPlugins( List parents ) private String getSafeProjectPathInfo( MavenProject project ) { - File file = project.getFile(); - if ( file != null ) - { - return file.getAbsolutePath(); - } - else - { - // path is used only as information in error message, we can fallback to project artifact info here - return project.toString(); - } + return ofNullable( project.getFile() ) + .map( File::getAbsolutePath ) + // path is used only as information in error message, + // we can fallback to project artifact info here + .orElse( project.toString() ); } private boolean isMavenPluginProject() @@ -853,12 +804,10 @@ private boolean isMavenPluginProject() private String compactKey( String groupId, String artifactId ) { - if ( PomHelper.APACHE_MAVEN_PLUGINS_GROUPID.equals( groupId ) ) - { - // a core plugin... group id is not needed - return artifactId; - } - return groupId + ":" + artifactId; + return PomHelper.APACHE_MAVEN_PLUGINS_GROUPID.equals( groupId ) + // a core plugin... group id is not needed + ? artifactId + : groupId + ":" + artifactId; } private static final class StackState @@ -882,19 +831,6 @@ public String toString() } } - /** - * Returns a set of Strings which correspond to the plugin coordinates where there is a version specified. - * - * @param project The project to get the plugins with versions specified. - * @return a set of Strings which correspond to the plugin coordinates where there is a version specified. - */ - private Set findPluginsWithVersionsSpecified( MavenProject project ) - throws IOException, XMLStreamException - { - return findPluginsWithVersionsSpecified( PomHelper.readXmlFile( project.getFile() ), - getSafeProjectPathInfo( project ) ); - } - /** * Returns a set of Strings which correspond to the plugin coordinates where there is a version specified. * @@ -903,13 +839,13 @@ private Set findPluginsWithVersionsSpecified( MavenProject project ) * @return a set of Strings which correspond to the plugin coordinates where there is a version specified. */ private Set findPluginsWithVersionsSpecified( StringBuilder pomContents, String path ) - throws XMLStreamException + throws XMLStreamException { Set result = new HashSet<>(); ModifiedPomXMLEventReader pom = newModifiedPomXER( pomContents, path ); Pattern pathRegex = Pattern.compile( "/project(/profiles/profile)?" - + "((/build(/pluginManagement)?)|(/reporting))" + "/plugins/plugin" ); + + "((/build(/pluginManagement)?)|(/reporting))" + "/plugins/plugin" ); Stack pathStack = new Stack<>(); StackState curState = null; while ( pom.hasNext() ) @@ -979,75 +915,48 @@ else if ( event.isEndElement() ) */ private ArtifactVersion getPrerequisitesMavenVersion( MavenProject pluginProject ) { - Prerequisites prerequisites = pluginProject.getPrerequisites(); - if ( null == prerequisites ) - { - return new DefaultArtifactVersion( "2.0" ); - } - - String prerequisitesMavenValue = prerequisites.getMaven(); - if ( null == prerequisitesMavenValue ) - { - return new DefaultArtifactVersion( "2.0" ); - } + return ofNullable( pluginProject.getPrerequisites() ) + .map( Prerequisites::getMaven ) + .map( DefaultArtifactVersion::new ) + .orElse( new DefaultArtifactVersion( "2.0" ) ); + } - return new DefaultArtifactVersion( prerequisitesMavenValue ); + /** + * Retrieves plugins from the given model + * + * @param build build + * @param onlyIncludeInherited {@code true} to only return the plugins definitions that will be inherited by + * child projects. + * @return map of plugin name x version + */ + private Map getPluginsFromBuild( BuildBase build, boolean onlyIncludeInherited ) + { + return ofNullable( build ) + .flatMap( b -> ofNullable( b.getPlugins() ) + .map( plugins -> plugins.stream() + .filter( plugin -> plugin.getVersion() != null ) + .filter( plugin -> !onlyIncludeInherited || getPluginInherited( plugin ) ) + .collect( toMap( Plugin::getKey, Plugin::getVersion ) ) ) ) + .orElse( emptyMap() ); } /** * Gets the build plugins of a specific project. * * @param model the model to get the build plugins from. - * @param onlyIncludeInherited true to only return the plugins definitions that will be inherited by + * @param onlyIncludeInherited {@code true} to only return the plugins definitions that will be inherited by * child projects. * @return The map of effective plugin versions keyed by coordinates. * @since 1.0-alpha-1 */ private Map getBuildPlugins( Model model, boolean onlyIncludeInherited ) { - Map buildPlugins = new HashMap<>(); - try - { - for ( Plugin plugin : model.getBuild().getPlugins() ) - { - String coord = plugin.getKey(); - String version = plugin.getVersion(); - if ( version != null && ( !onlyIncludeInherited || getPluginInherited( plugin ) ) ) - { - buildPlugins.put( coord, version ); - } - } - } - catch ( NullPointerException e ) - { - // guess there are no plugins here - } - try - { - for ( Profile profile : model.getProfiles() ) - { - try - { - for ( Plugin plugin : profile.getBuild().getPlugins() ) - { - String coord = plugin.getKey(); - String version = plugin.getVersion(); - if ( version != null && ( !onlyIncludeInherited || getPluginInherited( plugin ) ) ) - { - buildPlugins.put( coord, version ); - } - } - } - catch ( NullPointerException e ) - { - // guess there are no plugins here - } - } - } - catch ( NullPointerException e ) - { - // guess there are no profiles here - } + Map buildPlugins = + new HashMap<>( getPluginsFromBuild( model.getBuild(), onlyIncludeInherited ) ); + ofNullable( model.getProfiles() ) + .ifPresent( profiles -> profiles.stream() + .map( profile -> getPluginsFromBuild( profile.getBuild(), onlyIncludeInherited ) ) + .forEach( buildPlugins::putAll ) ); return buildPlugins; } @@ -1061,7 +970,7 @@ private Map getBuildPlugins( Model model, boolean onlyIncludeInh private static boolean getPluginInherited( Object plugin ) { return "true".equalsIgnoreCase( plugin instanceof ReportPlugin ? ( (ReportPlugin) plugin ).getInherited() - : ( (Plugin) plugin ).getInherited() ); + : ( (Plugin) plugin ).getInherited() ); } /** @@ -1073,35 +982,15 @@ private static boolean getPluginInherited( Object plugin ) * @since 1.0-alpha-1 */ private Map getLifecyclePlugins( MavenProject project ) - throws MojoExecutionException + throws MojoExecutionException { - Map lifecyclePlugins = new HashMap<>(); - try - { - Set plugins = getBoundPlugins( project, "clean,deploy,site" ); - for ( Plugin plugin : plugins ) - { - lifecyclePlugins.put( plugin.getKey(), plugin ); - } - } - catch ( PluginNotFoundException e ) - { - throw new MojoExecutionException( "Could not find plugin", e ); - } - catch ( LifecycleExecutionException e ) - { - throw new MojoExecutionException( "Could not determine lifecycle", e ); - } - catch ( IllegalAccessException e ) - { - throw new MojoExecutionException( "Could not determine lifecycles", e ); - } - catch ( NullPointerException e ) - { - // Maven 3.x - - } - return lifecyclePlugins; + return getBoundPlugins( project ) + .parallelStream() + .filter( Objects::nonNull ) + .filter( p -> p.getKey() != null ) + .collect( HashMap::new, + ( m, p ) -> m.put( p.getKey(), p ), + Map::putAll ); } /** @@ -1109,327 +998,22 @@ private Map getLifecyclePlugins( MavenProject project ) * later than the plugin is executing. * * @param project the project - * @param thePhases the the phases * @return the bound plugins - * @throws org.apache.maven.plugin.PluginNotFoundException the plugin not found exception - * @throws LifecycleExecutionException the lifecycle execution exception - * @throws IllegalAccessException the illegal access exception */ // pilfered this from enforcer-rules // TODO coordinate with Brian Fox to remove the duplicate code - private Set getBoundPlugins( MavenProject project, String thePhases ) - throws PluginNotFoundException, LifecycleExecutionException, IllegalAccessException + private Set getBoundPlugins( MavenProject project ) { - if ( new DefaultArtifactVersion( "3.0" ).compareTo( runtimeInformation.getApplicationVersion() ) <= 0 ) - { - getLog().debug( "Using Maven 3.0+ strategy to determine lifecycle defined plugins" ); - try - { - Method getPluginsBoundByDefaultToAllLifecycles = - LifecycleExecutor.class.getMethod( "getPluginsBoundByDefaultToAllLifecycles", - String.class ); - Set plugins = - (Set) getPluginsBoundByDefaultToAllLifecycles.invoke( lifecycleExecutor, new Object[] { - project.getPackaging() == null ? "jar" : project.getPackaging()} ); - // we need to provide a copy with the version blanked out so that inferring from super-pom - // works as for 2.x as 3.x fills in the version on us! - Set result = new LinkedHashSet<>( plugins.size() ); - for ( Plugin plugin : plugins ) - { - Plugin dup = new Plugin(); - dup.setGroupId( plugin.getGroupId() ); - dup.setArtifactId( plugin.getArtifactId() ); - result.add( dup ); - } - return result; - } - catch ( NoSuchMethodException | InvocationTargetException | IllegalAccessException e1 ) - { - // no much we can do here - } - } - List lifecycles = null; - getLog().debug( "Using Maven 2.0.10+ strategy to determine lifecycle defined plugins" ); - try - { - Method getLifecycles = LifecycleExecutor.class.getMethod( "getLifecycles" ); - lifecycles = (List) getLifecycles.invoke( lifecycleExecutor, new Object[0] ); - } - catch ( NoSuchMethodException | InvocationTargetException | IllegalAccessException e1 ) - { - // no much we can do here - } - - Set allPlugins = new HashSet<>(); - - // lookup the bindings for all the passed in phases - for ( String lifecyclePhase : thePhases.split( "," ) ) - { - if ( StringUtils.isNotEmpty( lifecyclePhase ) ) - { - try - { - Lifecycle lifecycle = getLifecycleForPhase( lifecycles, lifecyclePhase ); - allPlugins.addAll( getAllPlugins( project, lifecycle ) ); - } - catch ( BuildFailureException e ) - { - // i'm going to swallow this because the - // user may have declared a phase that - // doesn't exist for every module. - } - } - } - return allPlugins; - } - - /** - * Gets the lifecycle for phase. - * - * @param lifecycles The list of lifecycles. - * @param phase the phase - * @return the lifecycle for phase - * @throws BuildFailureException the build failure exception - * @throws LifecycleExecutionException the lifecycle execution exception - */ - private Lifecycle getLifecycleForPhase( List lifecycles, String phase ) - throws BuildFailureException, LifecycleExecutionException - { - Lifecycle lifecycle = getPhaseToLifecycleMap( lifecycles ).get( phase ); - - if ( lifecycle == null ) - { - throw new BuildFailureException( "Unable to find lifecycle for phase '" + phase + "'" ); - } - return lifecycle; - } - - /* - * Uses borrowed lifecycle code to get a list of all plugins bound to the lifecycle. - */ - - /** - * Gets the all plugins. - * - * @param project the project - * @param lifecycle the lifecycle - * @return the all plugins - * @throws PluginNotFoundException the plugin not found exception - * @throws LifecycleExecutionException the lifecycle execution exception - */ - private Set getAllPlugins( MavenProject project, Lifecycle lifecycle ) - throws PluginNotFoundException, LifecycleExecutionException - - { - Set plugins = new HashSet<>(); - // first, bind those associated with the packaging - Map mappings = findMappingsForLifecycle( project, lifecycle ); - - for ( Map.Entry entry : mappings.entrySet() ) - { - String value = (String) entry.getValue(); - String[] tokens = value.split( ":" ); - - Plugin plugin = new Plugin(); - plugin.setGroupId( tokens[0] ); - plugin.setArtifactId( tokens[1] ); - plugins.add( plugin ); - } - - for ( String value : findOptionalMojosForLifecycle( project, lifecycle ) ) - { - String[] tokens = value.split( ":" ); - - Plugin plugin = new Plugin(); - plugin.setGroupId( tokens[0] ); - plugin.setArtifactId( tokens[1] ); - plugins.add( plugin ); - } - - plugins.addAll( project.getBuildPlugins() ); - - return plugins; - } - - /** - * Find mappings for lifecycle. - * - * @param project the project - * @param lifecycle the lifecycle - * @return the map - * @throws LifecycleExecutionException the lifecycle execution exception - * @throws PluginNotFoundException the plugin not found exception - */ - private Map findMappingsForLifecycle( MavenProject project, Lifecycle lifecycle ) - throws LifecycleExecutionException, PluginNotFoundException - { - String packaging = project.getPackaging(); - Map mappings = null; - - LifecycleMapping m = (LifecycleMapping) findExtension( project, LifecycleMapping.ROLE, packaging, - session.getSettings(), session.getLocalRepository() ); - if ( m != null ) - { - mappings = m.getPhases( lifecycle.getId() ); - } - - Map defaultMappings = lifecycle.getDefaultPhases(); - - if ( mappings == null ) - { - try - { - m = (LifecycleMapping) session.lookup( LifecycleMapping.ROLE, packaging ); - mappings = m.getPhases( lifecycle.getId() ); - } - catch ( ComponentLookupException e ) - { - if ( defaultMappings == null ) - { - throw new LifecycleExecutionException( "Cannot find lifecycle mapping for packaging: '" + packaging - + "'.", e ); - } - } - } - - if ( mappings == null ) - { - if ( defaultMappings == null ) - { - throw new LifecycleExecutionException( "Cannot find lifecycle mapping for packaging: '" + packaging - + "', and there is no default" ); - } - else - { - mappings = defaultMappings; - } - } - - return mappings; - } - - /** - * Find optional mojos for lifecycle. - * - * @param project the project - * @param lifecycle the lifecycle - * @return the list - * @throws LifecycleExecutionException the lifecycle execution exception - * @throws PluginNotFoundException the plugin not found exception - */ - private List findOptionalMojosForLifecycle( MavenProject project, Lifecycle lifecycle ) - throws LifecycleExecutionException, PluginNotFoundException - { - String packaging = project.getPackaging(); - List optionalMojos = null; - - LifecycleMapping m = (LifecycleMapping) findExtension( project, LifecycleMapping.ROLE, packaging, - session.getSettings(), session.getLocalRepository() ); - - if ( m != null ) - { - optionalMojos = m.getOptionalMojos( lifecycle.getId() ); - } - - if ( optionalMojos == null ) - { - try - { - m = (LifecycleMapping) session.lookup( LifecycleMapping.ROLE, packaging ); - optionalMojos = m.getOptionalMojos( lifecycle.getId() ); - } - catch ( ComponentLookupException e ) - { - getLog().debug( "Error looking up lifecycle mapping to retrieve optional mojos. Lifecycle ID: " - + lifecycle.getId() + ". Error: " + e.getMessage(), e ); - } - } - - if ( optionalMojos == null ) - { - optionalMojos = Collections.emptyList(); - } - - return optionalMojos; - } - - /** - * Find extension. - * - * @param project the project - * @param role the role - * @param roleHint the role hint - * @param settings the settings - * @param localRepository the local repository - * @return the object - * @throws LifecycleExecutionException the lifecycle execution exception - * @throws PluginNotFoundException the plugin not found exception - */ - private Object findExtension( MavenProject project, String role, String roleHint, Settings settings, - ArtifactRepository localRepository ) - throws LifecycleExecutionException, PluginNotFoundException - { - Object pluginComponent = null; - - for ( Iterator i = project.getBuildPlugins().iterator(); i.hasNext() && pluginComponent == null; ) - { - Plugin plugin = (Plugin) i.next(); - - if ( plugin.isExtensions() ) - { - loadPluginDescriptor( plugin, project, session ); - - // TODO: if moved to the plugin manager we - // already have the descriptor from above - // and so do can lookup the container - // directly - try - { - pluginComponent = pluginManager.getPluginComponent( plugin, role, roleHint ); - } - catch ( ComponentLookupException e ) - { - getLog().debug( "Unable to find the lifecycle component in the extension", e ); - } - catch ( PluginManagerException e ) - { - throw new LifecycleExecutionException( "Error getting extensions from the plugin '" - + plugin.getKey() + "': " + e.getMessage(), e ); - } - } - } - return pluginComponent; - } - - /** - * Verify plugin. - * - * @param plugin the plugin - * @param project the project - * @param session the session - * @return the plugin descriptor - * @throws LifecycleExecutionException the lifecycle execution exception - * @throws PluginNotFoundException the plugin not found exception - */ - private PluginDescriptor loadPluginDescriptor( Plugin plugin, MavenProject project, MavenSession session ) - throws LifecycleExecutionException, PluginNotFoundException - { - PluginDescriptor pluginDescriptor; - try - { - pluginDescriptor = pluginManager.loadPluginDescriptor( plugin, project, session ); - } - catch ( PluginManagerException e ) - { - throw new LifecycleExecutionException( "Internal error in the plugin manager getting plugin '" - + plugin.getKey() + "': " + e.getMessage(), e ); - } - catch ( PluginVersionResolutionException | InvalidVersionSpecificationException | InvalidPluginException // - | ArtifactNotFoundException | ArtifactResolutionException | PluginVersionNotFoundException e ) - { - throw new LifecycleExecutionException( e.getMessage(), e ); - } - return pluginDescriptor; + // we need to provide a copy with the version blanked out so that inferring from super-pom + // works as for 2.x as 3.x fills in the version on us! + return lifecycleExecutor.getPluginsBoundByDefaultToAllLifecycles( project.getPackaging() ) + .parallelStream() + .map( p -> new Plugin() + {{ + setGroupId( p.getGroupId() ); + setArtifactId( p.getArtifactId() ); + }} ) + .collect( toSet() ); } /** @@ -1441,7 +1025,7 @@ private PluginDescriptor loadPluginDescriptor( Plugin plugin, MavenProject proje * @since 1.0-alpha-1 */ private List getParentProjects( MavenProject project ) - throws MojoExecutionException + throws MojoExecutionException { List parents = new ArrayList<>(); while ( project.getParent() != null ) @@ -1452,45 +1036,7 @@ private List getParentProjects( MavenProject project ) return parents; } - /* - * NOTE: All the code following this point was scooped from the DefaultLifecycleExecutor. There must be a better way - * but for now it should work. - */ - - /** - * Gets the phase to lifecycle map. - * - * @param lifecycles The list of lifecycles. - * @return the phase to lifecycle map. - * @throws LifecycleExecutionException the lifecycle execution exception. - */ - public Map getPhaseToLifecycleMap( List lifecycles ) - throws LifecycleExecutionException - { - Map phaseToLifecycleMap = new HashMap<>(); - - for ( Lifecycle lifecycle : lifecycles ) - { - for ( String phase : lifecycle.getPhases() ) - { - if ( phaseToLifecycleMap.containsKey( phase ) ) - { - Lifecycle prevLifecycle = phaseToLifecycleMap.get( phase ); - throw new LifecycleExecutionException( "Phase '" + phase - + "' is defined in more than one lifecycle: '" - + lifecycle.getId() + "' and '" - + prevLifecycle.getId() + "'" ); - } - else - { - phaseToLifecycleMap.put( phase, lifecycle ); - } - } - } - return phaseToLifecycleMap; - } - - /** + /** * Returns the set of all plugins used by the project. * * @param superPomPluginManagement the super pom's pluginManagement plugins. @@ -1507,7 +1053,7 @@ private Set getProjectPlugins( Map superPomPluginManagem Map parentBuildPlugins, Map parentReportPlugins, Set pluginsWithVersionsSpecified ) - throws MojoExecutionException + throws MojoExecutionException { Map plugins = new HashMap<>(); @@ -1544,13 +1090,13 @@ private Set getProjectPlugins( Map superPomPluginManagem ModelBuildingRequest modelBuildingRequest = new DefaultModelBuildingRequest(); modelBuildingRequest.setUserProperties( getProject().getProperties() ); Model originalModel = - modelInterpolator.interpolateModel( getProject().getOriginalModel(), getProject().getBasedir(), - modelBuildingRequest, new IgnoringModelProblemCollector() ); + modelInterpolator.interpolateModel( getProject().getOriginalModel(), getProject().getBasedir(), + modelBuildingRequest, new IgnoringModelProblemCollector() ); try { addProjectPlugins( plugins, originalModel.getBuild().getPluginManagement().getPlugins(), - excludePluginManagement ); + excludePluginManagement ); } catch ( NullPointerException e ) { @@ -1642,7 +1188,7 @@ private Set getProjectPlugins( Map superPomPluginManagem try { addProjectPlugins( plugins, profile.getBuild().getPluginManagement().getPlugins(), - excludePluginManagement ); + excludePluginManagement ); } catch ( NullPointerException e ) { @@ -1692,8 +1238,8 @@ private void addProjectPlugins( Map plugins, Collection String version = plugin.getVersion(); String parentVersion = parentDefinitions.get( coord ); if ( version == null - && ( !plugins.containsKey( coord ) || plugins.get( coord ).getVersion() == null ) - && parentVersion != null ) + && ( !plugins.containsKey( coord ) || plugins.get( coord ).getVersion() == null ) + && parentVersion != null ) { Plugin parentPlugin = new Plugin(); parentPlugin.setGroupId( plugin.getGroupId() ); diff --git a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/RevertMojo.java b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/RevertMojo.java index dd49650b40..1f232613b7 100644 --- a/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/RevertMojo.java +++ b/versions-maven-plugin/src/main/java/org/codehaus/mojo/versions/RevertMojo.java @@ -27,7 +27,6 @@ import java.nio.file.Paths; import java.util.Set; -import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; @@ -74,9 +73,6 @@ public class RevertMojo extends AbstractMojo */ protected final ProjectBuilder projectBuilder; - @Parameter( defaultValue = "${localRepository}", readonly = true ) - protected ArtifactRepository localRepository; - @Inject protected RevertMojo( ProjectBuilder projectBuilder ) { diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/PropertyUpdatesReportMojoTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/PropertyUpdatesReportMojoTest.java index c62ac79d10..89f0a75cc7 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/PropertyUpdatesReportMojoTest.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/PropertyUpdatesReportMojoTest.java @@ -28,7 +28,6 @@ import org.apache.maven.doxia.tools.SiteTool; import org.apache.maven.plugin.testing.AbstractMojoTestCase; import org.apache.maven.plugin.testing.MojoRule; -import org.apache.maven.plugin.testing.stubs.StubArtifactRepository; import org.junit.Rule; import org.junit.Test; @@ -47,7 +46,6 @@ public class PropertyUpdatesReportMojoTest extends AbstractMojoTestCase public MojoRule mojoRule = new MojoRule( this ); private static final org.eclipse.aether.RepositorySystem AETHER_REPOSITORY_SYSTEM = mockAetherRepositorySystem(); private static final SiteTool SITE_TOOL = mockSiteTool(); - private static final StubArtifactRepository LOCAL_REPOSITORY = new StubArtifactRepository( "" ); @Test public void testIncludeParentTrueShouldContainProperty() throws Exception @@ -59,7 +57,6 @@ public void testIncludeParentTrueShouldContainProperty() throws Exception (PropertyUpdatesReportMojo) mojoRule.lookupConfiguredMojo( new File( "src/test/resources/org/codehaus/mojo/display-property-updates/issue-367/child" ), "property-updates-report" ); - setVariableValueToObject( mojo, "localRepository", LOCAL_REPOSITORY ); setVariableValueToObject( mojo, "siteTool", SITE_TOOL ); setVariableValueToObject( mojo, "aetherRepositorySystem", AETHER_REPOSITORY_SYSTEM ); setVariableValueToObject( mojo, "includeParent", true ); @@ -82,7 +79,6 @@ public void testIncludeParentFalseShouldNotContainProperty() throws Exception (PropertyUpdatesReportMojo) mojoRule.lookupConfiguredMojo( new File( "src/test/resources/org/codehaus/mojo/display-property-updates/issue-367/child" ), "property-updates-report" ); - setVariableValueToObject( mojo, "localRepository", new StubArtifactRepository( "" ) ); setVariableValueToObject( mojo, "siteTool", SITE_TOOL ); setVariableValueToObject( mojo, "aetherRepositorySystem", AETHER_REPOSITORY_SYSTEM ); setVariableValueToObject( mojo, "includeParent", false ); diff --git a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UpdateParentMojoTest.java b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UpdateParentMojoTest.java index 2673a73bb2..f7a25407ee 100644 --- a/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UpdateParentMojoTest.java +++ b/versions-maven-plugin/src/test/java/org/codehaus/mojo/versions/UpdateParentMojoTest.java @@ -7,7 +7,6 @@ import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; -import org.apache.maven.artifact.resolver.ArtifactResolver; import org.apache.maven.artifact.versioning.ArtifactVersion; import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; import org.apache.maven.artifact.versioning.VersionRange; @@ -50,8 +49,6 @@ public class UpdateParentMojoTest private UpdateParentMojo mojo; - private ArtifactResolver artifactResolver; - private static RepositorySystem repositorySystem; private static org.eclipse.aether.RepositorySystem aetherRepositorySystem; diff --git a/versions-test/pom.xml b/versions-test/pom.xml index 1ddf047d9e..0c02d71fd5 100644 --- a/versions-test/pom.xml +++ b/versions-test/pom.xml @@ -36,10 +36,15 @@ org.apache.maven - maven-compat + maven-core ${mavenVersion} provided + + org.eclipse.aether + aether-api + 1.1.0 + org.apache.maven.doxia doxia-integration-tools