From a645b21523eb25f279ee965b802932cdd32a43b6 Mon Sep 17 00:00:00 2001 From: Slawomir Jaranowski Date: Tue, 28 Mar 2023 20:23:37 +0200 Subject: [PATCH] Move to new Enforcer API - require m-enforcer-p 3.2.0 fix #256 --- src/it/circular-simple/verify.groovy | 10 ++ src/it/mojo-1744/verify.groovy | 2 +- src/it/mojo-1853/verify.groovy | 2 +- src/it/mojo-1929/verify.groovy | 2 +- .../require-project-url-missing/verify.groovy | 2 +- .../require-project-url-present/verify.groovy | 2 +- .../require-project-url-regex/verify.groovy | 2 +- .../require-property-diverges/verify.groovy | 2 +- .../verify.groovy | 2 +- src/it/smokes/verify.bsh | 2 +- .../AbstractMojoHausEnforcerRule.java | 36 ------ .../AbstractResolveDependencies.java | 67 ++-------- .../BanCircularDependencies.java | 95 +++++--------- .../dependencies}/BanDuplicateClasses.java | 29 +++-- .../dependencies}/ClassFile.java | 2 +- .../dependencies}/ClassesWithSameName.java | 8 +- .../dependencies}/Dependency.java | 2 +- .../dependencies}/EnforceBytecodeVersion.java | 22 +++- .../dependencies}/InputStreamSupplier.java | 4 +- .../extraenforcer/dependencies}/JarUtils.java | 2 +- .../encoding}/RequireEncoding.java | 83 +++++------- .../model}/AbstractRequireRoles.java | 60 ++------- .../model}/RequireContributorRoles.java | 11 +- .../model}/RequireDeveloperRoles.java | 11 +- .../model}/RequireProjectUrl.java | 52 ++++---- .../model}/RequirePropertyDiverges.java | 120 +++++++----------- .../plugins/enforcer/RequireEncodingTest.java | 37 ------ .../dependencies}/ArtifactBuilder.java | 2 +- .../dependencies}/ClassFileHelper.java | 2 +- .../dependencies}/ClassFileTest.java | 2 +- .../ClassesWithSameNameTest.java | 9 +- .../EnforceBytecodeVersionTest.java | 2 +- .../dependencies}/JarUtilsTest.java | 4 +- .../encoding/RequireEncodingTest.java | 42 ++++++ .../it/BanDuplicateClassesLogParser.java | 4 +- .../it/package-info.java | 2 +- .../model}/AbstractRequireRolesTest.java | 2 +- .../model}/RequirePropertyDivergesTest.java | 81 ++++++------ .../model}/RequireRolesTest.java | 32 +++-- .../extraenforcer/model}/RuleXpp3DomTest.java | 22 +++- 40 files changed, 376 insertions(+), 499 deletions(-) create mode 100644 src/it/circular-simple/verify.groovy delete mode 100644 src/main/java/org/apache/maven/plugins/enforcer/AbstractMojoHausEnforcerRule.java rename src/main/java/org/{apache/maven/plugins/enforcer => codehaus/mojo/extraenforcer/dependencies}/AbstractResolveDependencies.java (78%) rename src/main/java/org/{apache/maven/plugins/enforcer => codehaus/mojo/extraenforcer/dependencies}/BanCircularDependencies.java (52%) rename src/main/java/org/{apache/maven/plugins/enforcer => codehaus/mojo/extraenforcer/dependencies}/BanDuplicateClasses.java (91%) rename src/main/java/org/{apache/maven/plugins/enforcer => codehaus/mojo/extraenforcer/dependencies}/ClassFile.java (98%) rename src/main/java/org/{apache/maven/plugins/enforcer => codehaus/mojo/extraenforcer/dependencies}/ClassesWithSameName.java (96%) rename src/main/java/org/codehaus/mojo/{enforcer => extraenforcer/dependencies}/Dependency.java (98%) rename src/main/java/org/{apache/maven/plugins/enforcer => codehaus/mojo/extraenforcer/dependencies}/EnforceBytecodeVersion.java (96%) rename src/main/java/org/{apache/maven/plugins/enforcer => codehaus/mojo/extraenforcer/dependencies}/InputStreamSupplier.java (91%) rename src/main/java/org/{apache/maven/plugins/enforcer => codehaus/mojo/extraenforcer/dependencies}/JarUtils.java (95%) rename src/main/java/org/{apache/maven/plugins/enforcer => codehaus/mojo/extraenforcer/encoding}/RequireEncoding.java (60%) rename src/main/java/org/{apache/maven/plugins/enforcer => codehaus/mojo/extraenforcer/model}/AbstractRequireRoles.java (79%) rename src/main/java/org/{apache/maven/plugins/enforcer => codehaus/mojo/extraenforcer/model}/RequireContributorRoles.java (85%) rename src/main/java/org/{apache/maven/plugins/enforcer => codehaus/mojo/extraenforcer/model}/RequireDeveloperRoles.java (85%) rename src/main/java/org/{apache/maven/plugins/enforcer => codehaus/mojo/extraenforcer/model}/RequireProjectUrl.java (61%) rename src/main/java/org/{apache/maven/plugins/enforcer => codehaus/mojo/extraenforcer/model}/RequirePropertyDiverges.java (82%) delete mode 100644 src/test/java/org/apache/maven/plugins/enforcer/RequireEncodingTest.java rename src/test/java/org/{apache/maven/plugins/enforcer => codehaus/mojo/extraenforcer/dependencies}/ArtifactBuilder.java (98%) rename src/test/java/org/{apache/maven/plugins/enforcer => codehaus/mojo/extraenforcer/dependencies}/ClassFileHelper.java (98%) rename src/test/java/org/{apache/maven/plugins/enforcer => codehaus/mojo/extraenforcer/dependencies}/ClassFileTest.java (95%) rename src/test/java/org/{apache/maven/plugins/enforcer => codehaus/mojo/extraenforcer/dependencies}/ClassesWithSameNameTest.java (97%) rename src/test/java/org/{apache/maven/plugins/enforcer => codehaus/mojo/extraenforcer/dependencies}/EnforceBytecodeVersionTest.java (95%) rename src/test/java/org/{apache/maven/plugins/enforcer => codehaus/mojo/extraenforcer/dependencies}/JarUtilsTest.java (89%) create mode 100644 src/test/java/org/codehaus/mojo/extraenforcer/encoding/RequireEncodingTest.java rename src/test/java/org/codehaus/mojo/{extraenforcerrules => extraenforcer}/it/BanDuplicateClassesLogParser.java (95%) rename src/test/java/org/codehaus/mojo/{extraenforcerrules => extraenforcer}/it/package-info.java (95%) rename src/test/java/org/{apache/maven/plugins/enforcer => codehaus/mojo/extraenforcer/model}/AbstractRequireRolesTest.java (97%) rename src/test/java/org/{apache/maven/plugins/enforcer => codehaus/mojo/extraenforcer/model}/RequirePropertyDivergesTest.java (80%) rename src/test/java/org/{apache/maven/plugins/enforcer => codehaus/mojo/extraenforcer/model}/RequireRolesTest.java (90%) rename src/test/java/org/{apache/maven/plugins/enforcer => codehaus/mojo/extraenforcer/model}/RuleXpp3DomTest.java (81%) diff --git a/src/it/circular-simple/verify.groovy b/src/it/circular-simple/verify.groovy new file mode 100644 index 00000000..97f683e5 --- /dev/null +++ b/src/it/circular-simple/verify.groovy @@ -0,0 +1,10 @@ +File file = new File(basedir, "build.log"); +assert file.exists(); + +String text = file.getText("utf-8"); + + +assert text.contains('ERROR] Rule 0: org.codehaus.mojo.extraenforcer.dependencies.BanCircularDependencies failed with message:') +assert text.contains('[ERROR] Circular Dependency found. Your project\'s groupId:artifactId combination must not exist in the list of direct or transitive dependencies.') + +return true; diff --git a/src/it/mojo-1744/verify.groovy b/src/it/mojo-1744/verify.groovy index a71b0458..d016ff05 100644 --- a/src/it/mojo-1744/verify.groovy +++ b/src/it/mojo-1744/verify.groovy @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -import org.codehaus.mojo.extraenforcerrules.it.BanDuplicateClassesLogParser; +import org.codehaus.mojo.extraenforcer.it.BanDuplicateClassesLogParser; File log = new File( basedir, 'build.log' ) assert log.exists() diff --git a/src/it/mojo-1853/verify.groovy b/src/it/mojo-1853/verify.groovy index 66c1c0f6..193be262 100644 --- a/src/it/mojo-1853/verify.groovy +++ b/src/it/mojo-1853/verify.groovy @@ -1,7 +1,7 @@ final File file = new File( basedir, "build.log" ); final String buf = file.getText("utf-8"); -assert buf.contains(/org.apache.maven.plugins.enforcer.RequirePropertyDiverges failed with message/); +assert buf.contains(/org.codehaus.mojo.extraenforcer.model.RequirePropertyDiverges failed with message/); assert buf.contains('Property \'project.url\' evaluates to \'http://company/company-parent-pom/child-fail'); diff --git a/src/it/mojo-1929/verify.groovy b/src/it/mojo-1929/verify.groovy index 66c1c0f6..193be262 100644 --- a/src/it/mojo-1929/verify.groovy +++ b/src/it/mojo-1929/verify.groovy @@ -1,7 +1,7 @@ final File file = new File( basedir, "build.log" ); final String buf = file.getText("utf-8"); -assert buf.contains(/org.apache.maven.plugins.enforcer.RequirePropertyDiverges failed with message/); +assert buf.contains(/org.codehaus.mojo.extraenforcer.model.RequirePropertyDiverges failed with message/); assert buf.contains('Property \'project.url\' evaluates to \'http://company/company-parent-pom/child-fail'); diff --git a/src/it/require-project-url-missing/verify.groovy b/src/it/require-project-url-missing/verify.groovy index fac389ba..0234428a 100644 --- a/src/it/require-project-url-missing/verify.groovy +++ b/src/it/require-project-url-missing/verify.groovy @@ -2,6 +2,6 @@ File file = new File( basedir, "build.log" ); assert file.exists(); String text = file.getText("utf-8"); -assert text.contains('org.apache.maven.plugins.enforcer.RequireProjectUrl failed with message'); +assert text.contains('org.codehaus.mojo.extraenforcer.model.RequireProjectUrl failed with message'); return true; diff --git a/src/it/require-project-url-present/verify.groovy b/src/it/require-project-url-present/verify.groovy index 79997df5..1a1ac546 100644 --- a/src/it/require-project-url-present/verify.groovy +++ b/src/it/require-project-url-present/verify.groovy @@ -2,6 +2,6 @@ File file = new File( basedir, "build.log" ); assert file.exists(); String text = file.getText("utf-8"); -assert !text.contains('org.apache.maven.plugins.enforcer.RequireProjectUrl failed with message'); +assert !text.contains('org.codehaus.mojo.extraenforcer.model.RequireProjectUrl failed with message'); return true; diff --git a/src/it/require-project-url-regex/verify.groovy b/src/it/require-project-url-regex/verify.groovy index fac389ba..0234428a 100644 --- a/src/it/require-project-url-regex/verify.groovy +++ b/src/it/require-project-url-regex/verify.groovy @@ -2,6 +2,6 @@ File file = new File( basedir, "build.log" ); assert file.exists(); String text = file.getText("utf-8"); -assert text.contains('org.apache.maven.plugins.enforcer.RequireProjectUrl failed with message'); +assert text.contains('org.codehaus.mojo.extraenforcer.model.RequireProjectUrl failed with message'); return true; diff --git a/src/it/require-property-diverges/verify.groovy b/src/it/require-property-diverges/verify.groovy index 37f99097..db1775ce 100644 --- a/src/it/require-property-diverges/verify.groovy +++ b/src/it/require-property-diverges/verify.groovy @@ -1,7 +1,7 @@ final File file = new File( basedir, "build.log" ); final String buf = file.getText( "utf-8" ); -assert buf.contains(/org.apache.maven.plugins.enforcer.RequirePropertyDiverges failed with message/); +assert buf.contains(/org.codehaus.mojo.extraenforcer.model.RequirePropertyDiverges failed with message/); assert buf.contains('Property \'project.issueManagement\' is required for this build and not defined in hierarchy at all.'); diff --git a/src/it/require-roles-missing-contributor/verify.groovy b/src/it/require-roles-missing-contributor/verify.groovy index f8322f9b..ffef20db 100644 --- a/src/it/require-roles-missing-contributor/verify.groovy +++ b/src/it/require-roles-missing-contributor/verify.groovy @@ -2,6 +2,6 @@ File file = new File( basedir, "build.log" ); assert file.exists(); String text = file.getText("utf-8"); -assert text.contains('org.apache.maven.plugins.enforcer.RequireContributorRoles failed with message'); +assert text.contains('org.codehaus.mojo.extraenforcer.model.RequireContributorRoles failed with message'); assert text.contains('Found no contributor representing role(s) \'[quality manager]\''); return true; diff --git a/src/it/smokes/verify.bsh b/src/it/smokes/verify.bsh index 34b53198..58c14a49 100644 --- a/src/it/smokes/verify.bsh +++ b/src/it/smokes/verify.bsh @@ -7,7 +7,7 @@ try File file = new File( basedir, "build.log" ); String buf = FileUtils.fileRead( file ); - Pattern p = Pattern.compile( "\\Qorg.apache.maven.plugins.enforcer.BanDuplicateClasses failed with message\\E" ); + Pattern p = Pattern.compile( "\\Qorg.codehaus.mojo.extraenforcer.dependencies.BanDuplicateClasses failed with message\\E" ); Matcher m = p.matcher( buf.toString() ); if ( !m.find() ) { diff --git a/src/main/java/org/apache/maven/plugins/enforcer/AbstractMojoHausEnforcerRule.java b/src/main/java/org/apache/maven/plugins/enforcer/AbstractMojoHausEnforcerRule.java deleted file mode 100644 index 73ea0097..00000000 --- a/src/main/java/org/apache/maven/plugins/enforcer/AbstractMojoHausEnforcerRule.java +++ /dev/null @@ -1,36 +0,0 @@ -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 org.apache.maven.enforcer.rule.api.EnforcerLevel; -import org.apache.maven.enforcer.rule.api.EnforcerRule2; - -abstract class AbstractMojoHausEnforcerRule implements EnforcerRule2 { - private EnforcerLevel level = EnforcerLevel.ERROR; - - @Override - public EnforcerLevel getLevel() { - return level; - } - - public void setLevel(EnforcerLevel level) { - this.level = level; - } -} diff --git a/src/main/java/org/apache/maven/plugins/enforcer/AbstractResolveDependencies.java b/src/main/java/org/codehaus/mojo/extraenforcer/dependencies/AbstractResolveDependencies.java similarity index 78% rename from src/main/java/org/apache/maven/plugins/enforcer/AbstractResolveDependencies.java rename to src/main/java/org/codehaus/mojo/extraenforcer/dependencies/AbstractResolveDependencies.java index 84bff26d..f8836be7 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/AbstractResolveDependencies.java +++ b/src/main/java/org/codehaus/mojo/extraenforcer/dependencies/AbstractResolveDependencies.java @@ -1,4 +1,4 @@ -package org.apache.maven.plugins.enforcer; +package org.codehaus.mojo.extraenforcer.dependencies; import java.util.ArrayList; import java.util.HashSet; @@ -8,18 +8,14 @@ import org.apache.maven.RepositoryUtils; import org.apache.maven.artifact.Artifact; -import org.apache.maven.enforcer.rule.api.EnforcerRule; +import org.apache.maven.enforcer.rule.api.AbstractEnforcerRule; 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.logging.Log; import org.apache.maven.project.DefaultProjectBuildingRequest; import org.apache.maven.project.ProjectBuildingRequest; import org.apache.maven.shared.dependency.graph.DependencyGraphBuilder; import org.apache.maven.shared.dependency.graph.DependencyGraphBuilderException; import org.apache.maven.shared.dependency.graph.DependencyNode; -import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; -import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.resolution.ArtifactRequest; import org.eclipse.aether.resolution.ArtifactResolutionException; @@ -31,32 +27,22 @@ * @author Robert Scholte * */ -public abstract class AbstractResolveDependencies extends AbstractMojoHausEnforcerRule { +abstract class AbstractResolveDependencies extends AbstractEnforcerRule { - private DependencyGraphBuilder graphBuilder; + private final MavenSession session; + private final RepositorySystem repositorySystem; - private MavenSession session; - private RepositorySystem repositorySystem; + private final DependencyGraphBuilder graphBuilder; - private EnforcerRuleHelper helper; - - public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { - this.helper = helper; + protected AbstractResolveDependencies( + MavenSession session, RepositorySystem repositorySystem, DependencyGraphBuilder graphBuilder) { + this.session = session; + this.repositorySystem = repositorySystem; + this.graphBuilder = graphBuilder; + } - // Get components - try { - repositorySystem = helper.getComponent(RepositorySystem.class); - graphBuilder = helper.getComponent(DependencyGraphBuilder.class); - } catch (ComponentLookupException e) { - throw new EnforcerRuleException("Unable to lookup DependencyTreeBuilder: ", e); - } - - // Resolve expressions - try { - session = (MavenSession) helper.evaluate("${session}"); - } catch (ExpressionEvaluationException e) { - throw new EnforcerRuleException("Unable to lookup an expression " + e.getLocalizedMessage(), e); - } + @Override + public void execute() throws EnforcerRuleException { ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest(session.getProjectBuildingRequest()); buildingRequest.setProject(session.getCurrentProject()); @@ -124,31 +110,6 @@ private void resolveArtifact(Artifact artifact) throws ArtifactResolutionExcepti artifact.setResolved(true); } - protected Log getLog() { - return helper.getLog(); - } - - /** - * {@inheritDoc} - */ - public boolean isCacheable() { - return false; - } - - /** - * {@inheritDoc} - */ - public boolean isResultValid(EnforcerRule enforcerRule) { - return false; - } - - /** - * {@inheritDoc} - */ - public String getCacheId() { - return "Does not matter as not cacheable"; - } - /** * Convert a wildcard into a regex. * diff --git a/src/main/java/org/apache/maven/plugins/enforcer/BanCircularDependencies.java b/src/main/java/org/codehaus/mojo/extraenforcer/dependencies/BanCircularDependencies.java similarity index 52% rename from src/main/java/org/apache/maven/plugins/enforcer/BanCircularDependencies.java rename to src/main/java/org/codehaus/mojo/extraenforcer/dependencies/BanCircularDependencies.java index 9d83058f..52d7a170 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/BanCircularDependencies.java +++ b/src/main/java/org/codehaus/mojo/extraenforcer/dependencies/BanCircularDependencies.java @@ -1,4 +1,4 @@ -package org.apache.maven.plugins.enforcer; +package org.codehaus.mojo.extraenforcer.dependencies; /* * Licensed to the Apache Software Foundation (ASF) under one @@ -19,82 +19,76 @@ * under the License. */ +import javax.inject.Inject; +import javax.inject.Named; + import java.util.HashSet; import java.util.Set; import org.apache.maven.artifact.Artifact; -import org.apache.maven.enforcer.rule.api.EnforcerRule; +import org.apache.maven.enforcer.rule.api.AbstractEnforcerRule; +import org.apache.maven.enforcer.rule.api.EnforcerRuleError; 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.logging.Log; import org.apache.maven.project.DefaultProjectBuildingRequest; import org.apache.maven.project.MavenProject; import org.apache.maven.project.ProjectBuildingRequest; import org.apache.maven.shared.dependency.graph.DependencyGraphBuilder; import org.apache.maven.shared.dependency.graph.DependencyGraphBuilderException; import org.apache.maven.shared.dependency.graph.DependencyNode; -import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; -import org.codehaus.plexus.component.repository.exception.ComponentLookupException; /** * Bans circular dependencies on the classpath. * * @since 1.0-alpha-4 */ -public class BanCircularDependencies extends AbstractMojoHausEnforcerRule { +@Named("banCircularDependencies") +public class BanCircularDependencies extends AbstractEnforcerRule { - private transient DependencyGraphBuilder graphBuilder; + private final DependencyGraphBuilder graphBuilder; + private final MavenProject project; + private final MavenSession session; private String message; + @Inject + public BanCircularDependencies(DependencyGraphBuilder graphBuilder, MavenProject project, MavenSession session) { + this.graphBuilder = graphBuilder; + this.project = project; + this.session = session; + } + /** * {@inheritDoc} */ - public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { - Log log = helper.getLog(); - - try { - graphBuilder = helper.getComponent(DependencyGraphBuilder.class); - } catch (ComponentLookupException e) { - throw new EnforcerRuleException("Unable to lookup DependencyGraphBuilder: ", e); - } - - try { - MavenProject project = (MavenProject) helper.evaluate("${project}"); - MavenSession session = (MavenSession) helper.evaluate("${session}"); - - ProjectBuildingRequest buildingRequest = - new DefaultProjectBuildingRequest(session.getProjectBuildingRequest()); - buildingRequest.setProject(project); - - Set artifacts = getDependenciesToCheck(buildingRequest); - if (artifacts != null) { - for (Artifact artifact : artifacts) { - log.debug("groupId: " + artifact.getGroupId() + project.getGroupId()); - if (artifact.getGroupId().equals(project.getGroupId())) { - log.debug("artifactId: " + artifact.getArtifactId() + " " + project.getArtifactId()); - if (artifact.getArtifactId().equals(project.getArtifactId())) { - throw new EnforcerRuleException(getErrorMessage() + "\n " + artifact.getGroupId() + ":" - + artifact.getArtifactId() + "\n "); - } + public void execute() throws EnforcerRuleException { + + ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest(session.getProjectBuildingRequest()); + buildingRequest.setProject(project); + + Set artifacts = getDependenciesToCheck(buildingRequest); + if (artifacts != null) { + for (Artifact artifact : artifacts) { + getLog().debug("groupId: " + artifact.getGroupId() + project.getGroupId()); + if (artifact.getGroupId().equals(project.getGroupId())) { + getLog().debug("artifactId: " + artifact.getArtifactId() + " " + project.getArtifactId()); + if (artifact.getArtifactId().equals(project.getArtifactId())) { + throw new EnforcerRuleException(getErrorMessage() + "\n " + artifact.getGroupId() + ":" + + artifact.getArtifactId() + "\n "); } } } - } catch (ExpressionEvaluationException e) { - log.error("Error checking for circular dependencies", e); - e.printStackTrace(); } } - protected Set getDependenciesToCheck(ProjectBuildingRequest buildingRequest) { + protected Set getDependenciesToCheck(ProjectBuildingRequest buildingRequest) throws EnforcerRuleError { Set dependencies; try { DependencyNode node = graphBuilder.buildDependencyGraph(buildingRequest, null); dependencies = getAllDescendants(node); } catch (DependencyGraphBuilderException e) { // otherwise we need to change the signature of this protected method - throw new RuntimeException(e); + throw new EnforcerRuleError(e); } return dependencies; } @@ -121,25 +115,4 @@ private String getErrorMessage() { } return message; } - - /** - * {@inheritDoc} - */ - public boolean isCacheable() { - return false; - } - - /** - * {@inheritDoc} - */ - public boolean isResultValid(EnforcerRule enforcerRule) { - return false; - } - - /** - * {@inheritDoc} - */ - public String getCacheId() { - return "Does not matter as not cacheable"; - } } diff --git a/src/main/java/org/apache/maven/plugins/enforcer/BanDuplicateClasses.java b/src/main/java/org/codehaus/mojo/extraenforcer/dependencies/BanDuplicateClasses.java similarity index 91% rename from src/main/java/org/apache/maven/plugins/enforcer/BanDuplicateClasses.java rename to src/main/java/org/codehaus/mojo/extraenforcer/dependencies/BanDuplicateClasses.java index 5ae78e47..af31cad2 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/BanDuplicateClasses.java +++ b/src/main/java/org/codehaus/mojo/extraenforcer/dependencies/BanDuplicateClasses.java @@ -1,4 +1,4 @@ -package org.apache.maven.plugins.enforcer; +package org.codehaus.mojo.extraenforcer.dependencies; /* * Licensed to the Apache Software Foundation (ASF) under one @@ -19,6 +19,9 @@ * under the License. */ +import javax.inject.Inject; +import javax.inject.Named; + import java.io.File; import java.io.IOException; import java.nio.file.Files; @@ -35,15 +38,19 @@ import java.util.regex.Pattern; import org.apache.maven.artifact.Artifact; +import org.apache.maven.enforcer.rule.api.EnforcerRuleError; import org.apache.maven.enforcer.rule.api.EnforcerRuleException; -import org.codehaus.mojo.enforcer.Dependency; +import org.apache.maven.execution.MavenSession; +import org.apache.maven.shared.dependency.graph.DependencyGraphBuilder; import org.codehaus.plexus.util.FileUtils; +import org.eclipse.aether.RepositorySystem; -import static org.apache.maven.plugins.enforcer.JarUtils.isJarFile; +import static org.codehaus.mojo.extraenforcer.dependencies.JarUtils.isJarFile; /** * Bans duplicate classes on the classpath. */ +@Named("banDuplicateClasses") public class BanDuplicateClasses extends AbstractResolveDependencies { /** @@ -85,6 +92,12 @@ public class BanDuplicateClasses extends AbstractResolveDependencies { */ private boolean ignoreWhenIdentical; + @Inject + protected BanDuplicateClasses( + MavenSession session, RepositorySystem repositorySystem, DependencyGraphBuilder graphBuilder) { + super(session, repositorySystem, graphBuilder); + } + @Override protected void handleArtifacts(Set artifacts) throws EnforcerRuleException { List ignorableDependencies = new ArrayList<>(); @@ -121,13 +134,11 @@ protected void handleArtifacts(Set artifacts) throws EnforcerRuleExcep Set duplicateClassNames = new HashSet<>(); for (Artifact o : artifacts) { if (scopes != null && !scopes.contains(o.getScope())) { - if (getLog().isDebugEnabled()) { - getLog().debug("Skipping " + o + " due to scope"); - } + getLog().debug(() -> "Skipping " + o + " due to scope"); continue; } File file = o.getFile(); - getLog().debug("Searching for duplicate classes in " + file); + getLog().debug(() -> "Searching for duplicate classes in " + file); if (file == null || !file.exists()) { getLog().warn("Could not find " + o + " at " + file); } else if (file.isDirectory()) { @@ -143,7 +154,7 @@ protected void handleArtifacts(Set artifacts) throws EnforcerRuleExcep ignorableDependencies); } } catch (IOException e) { - throw new EnforcerRuleException( + throw new EnforcerRuleError( "Unable to process dependency " + o + " due to " + e.getLocalizedMessage(), e); } } else if (isJarFile(o)) { @@ -163,7 +174,7 @@ protected void handleArtifacts(Set artifacts) throws EnforcerRuleExcep } } } catch (IOException e) { - throw new EnforcerRuleException( + throw new EnforcerRuleError( "Unable to process dependency " + o + " due to " + e.getLocalizedMessage(), e); } } diff --git a/src/main/java/org/apache/maven/plugins/enforcer/ClassFile.java b/src/main/java/org/codehaus/mojo/extraenforcer/dependencies/ClassFile.java similarity index 98% rename from src/main/java/org/apache/maven/plugins/enforcer/ClassFile.java rename to src/main/java/org/codehaus/mojo/extraenforcer/dependencies/ClassFile.java index bb6ec8e8..9e0d3818 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/ClassFile.java +++ b/src/main/java/org/codehaus/mojo/extraenforcer/dependencies/ClassFile.java @@ -1,4 +1,4 @@ -package org.apache.maven.plugins.enforcer; +package org.codehaus.mojo.extraenforcer.dependencies; /* * Licensed to the Apache Software Foundation (ASF) under one diff --git a/src/main/java/org/apache/maven/plugins/enforcer/ClassesWithSameName.java b/src/main/java/org/codehaus/mojo/extraenforcer/dependencies/ClassesWithSameName.java similarity index 96% rename from src/main/java/org/apache/maven/plugins/enforcer/ClassesWithSameName.java rename to src/main/java/org/codehaus/mojo/extraenforcer/dependencies/ClassesWithSameName.java index c7456b4d..d29c166c 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/ClassesWithSameName.java +++ b/src/main/java/org/codehaus/mojo/extraenforcer/dependencies/ClassesWithSameName.java @@ -1,4 +1,4 @@ -package org.apache.maven.plugins.enforcer; +package org.codehaus.mojo.extraenforcer.dependencies; /* * Licensed to the Apache Software Foundation (ASF) under one @@ -28,7 +28,7 @@ import java.util.Set; import org.apache.maven.artifact.Artifact; -import org.apache.maven.plugin.logging.Log; +import org.apache.maven.enforcer.rule.api.EnforcerLogger; /** * Represents one or more class files that have the same exact name. @@ -45,7 +45,7 @@ * way (mockito-all) but not both. */ public class ClassesWithSameName { - private final Log log; + private final EnforcerLogger log; /** the path to the .class file. Example: org/apache/maven/Stuff.class */ private final String classFilePath; @@ -57,7 +57,7 @@ public class ClassesWithSameName { * next one lets us require at least one at compile time (instead of runtime). * @param additionalClassFiles (optional) additional class files */ - public ClassesWithSameName(Log log, ClassFile initialClassFile, ClassFile... additionalClassFiles) { + public ClassesWithSameName(EnforcerLogger log, ClassFile initialClassFile, ClassFile... additionalClassFiles) { this.log = log; classFilePath = initialClassFile.getClassFilePath(); list.add(initialClassFile); diff --git a/src/main/java/org/codehaus/mojo/enforcer/Dependency.java b/src/main/java/org/codehaus/mojo/extraenforcer/dependencies/Dependency.java similarity index 98% rename from src/main/java/org/codehaus/mojo/enforcer/Dependency.java rename to src/main/java/org/codehaus/mojo/extraenforcer/dependencies/Dependency.java index d04ebec2..c24bc663 100644 --- a/src/main/java/org/codehaus/mojo/enforcer/Dependency.java +++ b/src/main/java/org/codehaus/mojo/extraenforcer/dependencies/Dependency.java @@ -1,4 +1,4 @@ -package org.codehaus.mojo.enforcer; +package org.codehaus.mojo.extraenforcer.dependencies; /* * Licensed to the Apache Software Foundation (ASF) under one diff --git a/src/main/java/org/apache/maven/plugins/enforcer/EnforceBytecodeVersion.java b/src/main/java/org/codehaus/mojo/extraenforcer/dependencies/EnforceBytecodeVersion.java similarity index 96% rename from src/main/java/org/apache/maven/plugins/enforcer/EnforceBytecodeVersion.java rename to src/main/java/org/codehaus/mojo/extraenforcer/dependencies/EnforceBytecodeVersion.java index 12e39f8a..0193d7b2 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/EnforceBytecodeVersion.java +++ b/src/main/java/org/codehaus/mojo/extraenforcer/dependencies/EnforceBytecodeVersion.java @@ -1,4 +1,4 @@ -package org.apache.maven.plugins.enforcer; +package org.codehaus.mojo.extraenforcer.dependencies; /* * Licensed to the Apache Software Foundation (ASF) under one @@ -19,6 +19,9 @@ * under the License. */ +import javax.inject.Inject; +import javax.inject.Named; + import java.io.EOFException; import java.io.File; import java.io.IOException; @@ -40,11 +43,13 @@ import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.resolver.filter.AndArtifactFilter; import org.apache.maven.enforcer.rule.api.EnforcerRuleException; -import org.apache.maven.plugin.logging.Log; +import org.apache.maven.execution.MavenSession; import org.apache.maven.shared.artifact.filter.AbstractStrictPatternArtifactFilter; import org.apache.maven.shared.artifact.filter.StrictPatternExcludesArtifactFilter; import org.apache.maven.shared.artifact.filter.StrictPatternIncludesArtifactFilter; +import org.apache.maven.shared.dependency.graph.DependencyGraphBuilder; import org.codehaus.plexus.util.IOUtil; +import org.eclipse.aether.RepositorySystem; /** * Enforcer rule that will check the bytecode version of each class of each dependency. @@ -52,6 +57,7 @@ * @see Java class file general layout * @since 1.0-alpha-4 */ +@Named("enforceBytecodeVersion") public class EnforceBytecodeVersion extends AbstractResolveDependencies { private static final Map JDK_TO_MAJOR_VERSION_NUMBER_MAPPING = new LinkedHashMap<>(); /** @@ -125,6 +131,12 @@ public class EnforceBytecodeVersion extends AbstractResolveDependencies { JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.put("21", 65); } + @Inject + protected EnforceBytecodeVersion( + MavenSession session, RepositorySystem repositorySystem, DependencyGraphBuilder graphBuilder) { + super(session, repositorySystem, graphBuilder); + } + static String renderVersion(int major, int minor) { if (minor == 0) { for (Map.Entry entry : JDK_TO_MAJOR_VERSION_NUMBER_MAPPING.entrySet()) { @@ -195,7 +207,7 @@ protected void handleArtifacts(Set artifacts) throws EnforcerRuleExcep computeParameters(); // look for banned dependencies - Set foundExcludes = checkDependencies(filterArtifacts(artifacts), getLog()); + Set foundExcludes = checkDependencies(filterArtifacts(artifacts)); // if any are found, fail the check but list all of them if (foundExcludes != null && !foundExcludes.isEmpty()) { @@ -254,7 +266,7 @@ private void computeParameters() throws EnforcerRuleException { } } - protected Set checkDependencies(Set dependencies, Log log) throws EnforcerRuleException { + protected Set checkDependencies(Set dependencies) throws EnforcerRuleException { long beforeCheck = System.currentTimeMillis(); Set problematic = new LinkedHashSet<>(); for (Artifact artifact : dependencies) { @@ -360,7 +372,7 @@ private void closeQuietly(JarFile jarFile) { try { jarFile.close(); } catch (IOException ioe) { - getLog().warn("Exception catched while closing " + jarFile.getName(), ioe); + getLog().warn("Exception catched while closing " + jarFile.getName() + ": " + ioe.getMessage()); } } } diff --git a/src/main/java/org/apache/maven/plugins/enforcer/InputStreamSupplier.java b/src/main/java/org/codehaus/mojo/extraenforcer/dependencies/InputStreamSupplier.java similarity index 91% rename from src/main/java/org/apache/maven/plugins/enforcer/InputStreamSupplier.java rename to src/main/java/org/codehaus/mojo/extraenforcer/dependencies/InputStreamSupplier.java index 1bea54d4..ef3832d7 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/InputStreamSupplier.java +++ b/src/main/java/org/codehaus/mojo/extraenforcer/dependencies/InputStreamSupplier.java @@ -1,4 +1,4 @@ -package org.apache.maven.plugins.enforcer; +package org.codehaus.mojo.extraenforcer.dependencies; /* * Licensed to the Apache Software Foundation (ASF) under one @@ -28,6 +28,6 @@ * @author Slawomir Jaranowski */ @FunctionalInterface -interface InputStreamSupplier { +public interface InputStreamSupplier { InputStream get() throws IOException; } diff --git a/src/main/java/org/apache/maven/plugins/enforcer/JarUtils.java b/src/main/java/org/codehaus/mojo/extraenforcer/dependencies/JarUtils.java similarity index 95% rename from src/main/java/org/apache/maven/plugins/enforcer/JarUtils.java rename to src/main/java/org/codehaus/mojo/extraenforcer/dependencies/JarUtils.java index 09377b01..e49e5950 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/JarUtils.java +++ b/src/main/java/org/codehaus/mojo/extraenforcer/dependencies/JarUtils.java @@ -1,4 +1,4 @@ -package org.apache.maven.plugins.enforcer; +package org.codehaus.mojo.extraenforcer.dependencies; /* * Licensed to the Apache Software Foundation (ASF) under one diff --git a/src/main/java/org/apache/maven/plugins/enforcer/RequireEncoding.java b/src/main/java/org/codehaus/mojo/extraenforcer/encoding/RequireEncoding.java similarity index 60% rename from src/main/java/org/apache/maven/plugins/enforcer/RequireEncoding.java rename to src/main/java/org/codehaus/mojo/extraenforcer/encoding/RequireEncoding.java index 18998ca0..635367e7 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/RequireEncoding.java +++ b/src/main/java/org/codehaus/mojo/extraenforcer/encoding/RequireEncoding.java @@ -1,4 +1,7 @@ -package org.apache.maven.plugins.enforcer; +package org.codehaus.mojo.extraenforcer.encoding; + +import javax.inject.Inject; +import javax.inject.Named; import java.io.File; import java.io.IOException; @@ -8,11 +11,10 @@ import java.util.HashSet; import java.util.Set; -import org.apache.maven.enforcer.rule.api.EnforcerRule; +import org.apache.maven.enforcer.rule.api.AbstractEnforcerRule; +import org.apache.maven.enforcer.rule.api.EnforcerRuleError; import org.apache.maven.enforcer.rule.api.EnforcerRuleException; -import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; -import org.apache.maven.plugin.logging.Log; -import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; +import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.DirectoryScanner; import org.codehaus.plexus.util.StringUtils; import org.freebsd.file.FileEncoding; @@ -24,7 +26,8 @@ * @see mikedon/encoding-enforcer * @see ericbn/encoding-enforcer */ -public class RequireEncoding extends AbstractMojoHausEnforcerRule { +@Named("requireEncoding") +public class RequireEncoding extends AbstractEnforcerRule { private static final String ISO_8859_15 = "ISO-8859-15"; /** @@ -62,16 +65,23 @@ public class RequireEncoding extends AbstractMojoHausEnforcerRule { */ private boolean acceptIso8859Subset = false; - public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { + private final MavenProject project; + + @Inject + public RequireEncoding(MavenProject project) { + this.project = project; + } + + @Override + public void execute() throws EnforcerRuleException { try { if (StringUtils.isBlank(encoding)) { - encoding = (String) helper.evaluate("${project.build.sourceEncoding}"); + encoding = project.getProperties().getProperty("project.build.sourceEncoding", ""); } - Log log = helper.getLog(); Set acceptedEncodings = new HashSet<>(Collections.singletonList(encoding)); if (encoding.equals(StandardCharsets.US_ASCII.name())) { - log.warn("Encoding US-ASCII is hard to detect. Use UTF-8 or ISO-8859-1"); + getLog().warn("Encoding US-ASCII is hard to detect. Use UTF-8 or ISO-8859-1"); } if (acceptAsciiSubset @@ -84,7 +94,7 @@ public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { acceptedEncodings.add("ISO-8859-1"); } - String basedir = (String) helper.evaluate("${basedir}"); + String basedir = project.getBasedir().getAbsolutePath(); DirectoryScanner ds = new DirectoryScanner(); ds.setBasedir(basedir); if (StringUtils.isNotBlank(includes)) { @@ -99,15 +109,13 @@ public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { ds.scan(); StringBuilder filesInMsg = new StringBuilder(); for (String file : ds.getIncludedFiles()) { - String fileEncoding = getEncoding(encoding, new File(basedir, file), log); - if (log.isDebugEnabled()) { - log.debug(file + "==>" + fileEncoding); - } + String fileEncoding = getEncoding(new File(basedir, file)); + getLog().debug(() -> file + "==>" + fileEncoding); if (fileEncoding != null && !acceptedEncodings.contains(fileEncoding)) { filesInMsg.append(file); filesInMsg.append("==>"); filesInMsg.append(fileEncoding); - filesInMsg.append("\n"); + filesInMsg.append(System.lineSeparator()); if (failFast) { throw new EnforcerRuleException(filesInMsg.toString()); } @@ -117,56 +125,23 @@ public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { throw new EnforcerRuleException("Files not encoded in " + encoding + ":\n" + filesInMsg); } } catch (IOException ex) { - throw new EnforcerRuleException("Reading Files", ex); - } catch (ExpressionEvaluationException e) { - throw new EnforcerRuleException("Unable to lookup an expression " + e.getLocalizedMessage(), e); + throw new EnforcerRuleError("Reading Files", ex); } } - protected String getEncoding(String requiredEncoding, File file, Log log) throws IOException { + protected String getEncoding(File file) throws IOException { FileEncoding fileEncoding = new FileEncoding(); if (!fileEncoding.guessFileEncoding(Files.readAllBytes(file.toPath()))) { return null; } - if (log.isDebugEnabled()) { - log.debug(String.format( - "%s: (%s) %s; charset=%s", - file, fileEncoding.getCode(), fileEncoding.getType(), fileEncoding.getCodeMime())); - } + getLog().debug(() -> String.format( + "%s: (%s) %s; charset=%s", + file, fileEncoding.getCode(), fileEncoding.getType(), fileEncoding.getCodeMime())); return fileEncoding.getCodeMime().toUpperCase(); } - /** - * If your rule is cacheable, you must return a unique id when parameters or conditions change that would cause the - * result to be different. Multiple cached results are stored based on their id. The easiest way to do this is to - * return a hash computed from the values of your parameters. If your rule is not cacheable, then the result here is - * not important, you may return anything. - */ - public String getCacheId() { - return null; - } - - /** - * This tells the system if the results are cacheable at all. Keep in mind that during forked builds and other - * things, a given rule may be executed more than once for the same project. This means that even things that change - * from project to project may still be cacheable in certain instances. - */ - public boolean isCacheable() { - return false; - } - - /** - * If the rule is cacheable and the same id is found in the cache, the stored results are passed to this method to - * allow double checking of the results. Most of the time this can be done by generating unique ids, but sometimes - * the results of objects returned by the helper need to be queried. You may for example, store certain objects in - * your rule and then query them later. - */ - public boolean isResultValid(EnforcerRule cachedRule) { - return false; - } - public String getEncoding() { return encoding; } diff --git a/src/main/java/org/apache/maven/plugins/enforcer/AbstractRequireRoles.java b/src/main/java/org/codehaus/mojo/extraenforcer/model/AbstractRequireRoles.java similarity index 79% rename from src/main/java/org/apache/maven/plugins/enforcer/AbstractRequireRoles.java rename to src/main/java/org/codehaus/mojo/extraenforcer/model/AbstractRequireRoles.java index 2581bbfa..6977277a 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/AbstractRequireRoles.java +++ b/src/main/java/org/codehaus/mojo/extraenforcer/model/AbstractRequireRoles.java @@ -1,4 +1,4 @@ -package org.apache.maven.plugins.enforcer; +package org.codehaus.mojo.extraenforcer.model; /* * Licensed to the Apache Software Foundation (ASF) under one @@ -25,13 +25,11 @@ import java.util.List; import java.util.Set; -import org.apache.maven.enforcer.rule.api.EnforcerRule; +import org.apache.maven.enforcer.rule.api.AbstractEnforcerRule; import org.apache.maven.enforcer.rule.api.EnforcerRuleException; -import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; import org.apache.maven.model.Contributor; import org.apache.maven.model.Developer; import org.apache.maven.project.MavenProject; -import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; import org.codehaus.plexus.util.StringUtils; /** @@ -40,7 +38,7 @@ * @author Mirko Friedenhagen * @since 1.0-alpha-3 */ -abstract class AbstractRequireRoles extends AbstractMojoHausEnforcerRule { +abstract class AbstractRequireRoles extends AbstractEnforcerRule { /** * Specify the required roles as comma separated list. */ @@ -51,18 +49,23 @@ abstract class AbstractRequireRoles extends AbstractMojoH */ private String validRoles = "*"; + private final MavenProject project; + + AbstractRequireRoles(MavenProject project) { + this.project = project; + } + /** * Execute the rule. * - * @param helper the helper * @throws EnforcerRuleException the enforcer rule exception */ - public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { - MavenProject mavenProject = getMavenProject(helper); + @Override + public void execute() throws EnforcerRuleException { // Trying to prevent side-effects with unmodifiable sets (already got burned) final Set requiredRolesSet = Collections.unmodifiableSet(getRolesFromString(requiredRoles)); - final Set rolesFromProject = Collections.unmodifiableSet(getRolesFromProject(mavenProject)); + final Set rolesFromProject = Collections.unmodifiableSet(getRolesFromProject(project)); checkRequiredRoles(requiredRolesSet, rolesFromProject); checkValidRoles(requiredRolesSet, rolesFromProject); @@ -146,22 +149,6 @@ static Set splitCsvToSet(final String csv) { return result; } - /** - * Extracted for easier testability. - * - * @param helper - * @return the MavenProject enforcer is running on. - * - * @throws EnforcerRuleException - */ - MavenProject getMavenProject(EnforcerRuleHelper helper) throws EnforcerRuleException { - try { - return (MavenProject) helper.evaluate("${project}"); - } catch (ExpressionEvaluationException eee) { - throw new EnforcerRuleException("Unable to get project.", eee); - } - } - // HELPER methods for unittests. /** * @param requiredRoles the requiredRoles to set. @@ -173,27 +160,4 @@ void setRequiredRoles(String requiredRoles) { void setValidRoles(String validRoles) { this.validRoles = validRoles; } - - // ********************* - - /** - * {@inheritDoc} - */ - public String getCacheId() { - return "0"; - } - - /** - * {@inheritDoc} - */ - public boolean isCacheable() { - return false; - } - - /** - * {@inheritDoc} - */ - public boolean isResultValid(EnforcerRule cachedRule) { - return false; - } } diff --git a/src/main/java/org/apache/maven/plugins/enforcer/RequireContributorRoles.java b/src/main/java/org/codehaus/mojo/extraenforcer/model/RequireContributorRoles.java similarity index 85% rename from src/main/java/org/apache/maven/plugins/enforcer/RequireContributorRoles.java rename to src/main/java/org/codehaus/mojo/extraenforcer/model/RequireContributorRoles.java index 081e5540..b513256e 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/RequireContributorRoles.java +++ b/src/main/java/org/codehaus/mojo/extraenforcer/model/RequireContributorRoles.java @@ -1,4 +1,4 @@ -package org.apache.maven.plugins.enforcer; +package org.codehaus.mojo.extraenforcer.model; /* * Licensed to the Apache Software Foundation (ASF) under one @@ -19,6 +19,9 @@ * under the License. */ +import javax.inject.Inject; +import javax.inject.Named; + import java.util.List; import org.apache.maven.model.Contributor; @@ -30,8 +33,14 @@ * @author Mirko Friedenhagen * @since 1.0-alpha-3 */ +@Named("requireContributorRoles") public class RequireContributorRoles extends AbstractRequireRoles { + @Inject + public RequireContributorRoles(MavenProject project) { + super(project); + } + @Override protected final String getRoleName() { return "contributor"; diff --git a/src/main/java/org/apache/maven/plugins/enforcer/RequireDeveloperRoles.java b/src/main/java/org/codehaus/mojo/extraenforcer/model/RequireDeveloperRoles.java similarity index 85% rename from src/main/java/org/apache/maven/plugins/enforcer/RequireDeveloperRoles.java rename to src/main/java/org/codehaus/mojo/extraenforcer/model/RequireDeveloperRoles.java index 73801dff..b5a479f3 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/RequireDeveloperRoles.java +++ b/src/main/java/org/codehaus/mojo/extraenforcer/model/RequireDeveloperRoles.java @@ -1,4 +1,4 @@ -package org.apache.maven.plugins.enforcer; +package org.codehaus.mojo.extraenforcer.model; /* * Licensed to the Apache Software Foundation (ASF) under one @@ -19,6 +19,9 @@ * under the License. */ +import javax.inject.Inject; +import javax.inject.Named; + import java.util.List; import org.apache.maven.model.Developer; @@ -30,8 +33,14 @@ * @author Mirko Friedenhagen * @since 1.0-alpha-3 */ +@Named("requireDeveloperRoles") public class RequireDeveloperRoles extends AbstractRequireRoles { + @Inject + public RequireDeveloperRoles(MavenProject project) { + super(project); + } + @Override protected String getRoleName() { return "developer"; diff --git a/src/main/java/org/apache/maven/plugins/enforcer/RequireProjectUrl.java b/src/main/java/org/codehaus/mojo/extraenforcer/model/RequireProjectUrl.java similarity index 61% rename from src/main/java/org/apache/maven/plugins/enforcer/RequireProjectUrl.java rename to src/main/java/org/codehaus/mojo/extraenforcer/model/RequireProjectUrl.java index be65a9dd..0a53c4ef 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/RequireProjectUrl.java +++ b/src/main/java/org/codehaus/mojo/extraenforcer/model/RequireProjectUrl.java @@ -1,4 +1,4 @@ -package org.apache.maven.plugins.enforcer; +package org.codehaus.mojo.extraenforcer.model; /* * Licensed to the Apache Software Foundation (ASF) under one @@ -19,31 +19,41 @@ * under the License. */ +import javax.inject.Inject; +import javax.inject.Named; + +import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; -import org.apache.maven.enforcer.rule.api.EnforcerRule; +import org.apache.maven.enforcer.rule.api.AbstractEnforcerRule; +import org.apache.maven.enforcer.rule.api.EnforcerRuleError; import org.apache.maven.enforcer.rule.api.EnforcerRuleException; -import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; import org.apache.maven.project.MavenProject; -import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; /** * This rule enforces the presence of an URL and optionally matches the URL against a regex * * @since 1.0-beta-4 */ -public class RequireProjectUrl extends AbstractMojoHausEnforcerRule { +@Named("requireProjectUrl") +public class RequireProjectUrl extends AbstractEnforcerRule { /** * The regex that the url must match. Default is a non-empty URL */ private String regex = "^.+$"; - public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { - MavenProject project; + private final MavenProject project; + + @Inject + RequireProjectUrl(MavenProject project) { + this.project = Objects.requireNonNull(project); + } + + @Override + public void execute() throws EnforcerRuleException { try { - project = (MavenProject) helper.evaluate("${project}"); if (project.getUrl() == null) { throw new EnforcerRuleException("The project URL is not defined"); } @@ -52,31 +62,13 @@ public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { throw new EnforcerRuleException( "The project URL " + project.getUrl() + " does not match the required regex: " + regex); } - } catch (ExpressionEvaluationException e) { - throw new EnforcerRuleException("Unable to lookup an expression " + e.getLocalizedMessage(), e); } catch (PatternSyntaxException e) { - throw new EnforcerRuleException("Invalid regex \"" + regex + "\": " + e.getLocalizedMessage(), e); + throw new EnforcerRuleError("Invalid regex \"" + regex + "\": " + e.getLocalizedMessage(), e); } } - /** - * {@inheritDoc} - */ - public boolean isCacheable() { - return false; - } - - /** - * {@inheritDoc} - */ - public boolean isResultValid(EnforcerRule enforcerRule) { - return false; - } - - /** - * {@inheritDoc} - */ - public String getCacheId() { - return "Does not matter as not cacheable"; + @Override + public String toString() { + return String.format("RequireProjectUrl[regex=%s]", regex); } } diff --git a/src/main/java/org/apache/maven/plugins/enforcer/RequirePropertyDiverges.java b/src/main/java/org/codehaus/mojo/extraenforcer/model/RequirePropertyDiverges.java similarity index 82% rename from src/main/java/org/apache/maven/plugins/enforcer/RequirePropertyDiverges.java rename to src/main/java/org/codehaus/mojo/extraenforcer/model/RequirePropertyDiverges.java index c49f7c6a..2634a3f1 100644 --- a/src/main/java/org/apache/maven/plugins/enforcer/RequirePropertyDiverges.java +++ b/src/main/java/org/codehaus/mojo/extraenforcer/model/RequirePropertyDiverges.java @@ -1,4 +1,4 @@ -package org.apache.maven.plugins.enforcer; +package org.codehaus.mojo.extraenforcer.model; /* * Licensed to the Apache Software Foundation (ASF) under one @@ -18,6 +18,10 @@ * specific language governing permissions and limitations * under the License. */ + +import javax.inject.Inject; +import javax.inject.Named; + import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -25,57 +29,67 @@ import java.util.SortedMap; import java.util.TreeMap; -import org.apache.maven.enforcer.rule.api.EnforcerRule; +import org.apache.maven.enforcer.rule.api.AbstractEnforcerRule; +import org.apache.maven.enforcer.rule.api.EnforcerRuleError; import org.apache.maven.enforcer.rule.api.EnforcerRuleException; -import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; import org.apache.maven.model.Build; import org.apache.maven.model.Model; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; import org.apache.maven.model.PluginManagement; -import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; +import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.xml.Xpp3Dom; /** * This rule checks that certain properties are set and diverge from the ones given in another project. - * * This allows to enforce that a property is e.g. overridden in a child project. * * @author Mirko Friedenhagen * @since 1.0-alpha-3 */ -public class RequirePropertyDiverges extends AbstractMojoHausEnforcerRule { +@Named("requirePropertyDiverges") +public class RequirePropertyDiverges extends AbstractEnforcerRule { private String message; static final String MAVEN_ENFORCER_PLUGIN = "org.apache.maven.plugins:maven-enforcer-plugin"; + /** * Specify the required property. Must be given. */ private String property = null; + /** * Match the property value to a given regular expression. Defaults to value of defining project. */ private String regex = null; - private final String ruleName = StringUtils.lowercaseFirstLetter(getClass().getSimpleName()); + private static final String RULE_NAME = + StringUtils.lowercaseFirstLetter(RequirePropertyDiverges.class.getSimpleName()); + + private final MavenProject project; + + private final ExpressionEvaluator evaluator; + + @Inject + public RequirePropertyDiverges(MavenProject project, ExpressionEvaluator evaluator) { + this.project = project; + this.evaluator = evaluator; + } /** * Execute the rule. * - * @param helper the helper * @throws EnforcerRuleException the enforcer rule exception */ - public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { - final Log log = helper.getLog(); + public void execute() throws EnforcerRuleException { - Object propValue = getPropertyValue(helper); + Object propValue = getPropertyValue(); checkPropValueNotBlank(propValue); - final MavenProject project = getMavenProject(helper); - log.debug(getRuleName() + ": checking property '" + property + "' for project " + project); + getLog().debug(() -> getRuleName() + ": checking property '" + property + "' for project " + project); final MavenProject parent = findDefiningParent(project); @@ -85,11 +99,12 @@ public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { } if (project.equals(parent)) { - log.debug(getRuleName() + ": skip for property '" + property + "' as " + project + " defines rule."); + getLog().debug(() -> + getRuleName() + ": skip for property '" + property + "' as " + project + " defines rule."); } else { - log.debug("Check configuration defined in " + parent); + getLog().debug(() -> "Check configuration defined in " + parent); if (regex == null) { - checkAgainstParentValue(project, parent, helper, propValue); + checkAgainstParentValue(project, parent, propValue); } else { checkAgainstRegex(propValue); } @@ -101,12 +116,10 @@ public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { * * @param project * @param parent - * @param helper * @param propValue * @throws EnforcerRuleException */ - void checkAgainstParentValue( - final MavenProject project, final MavenProject parent, EnforcerRuleHelper helper, Object propValue) + void checkAgainstParentValue(final MavenProject project, final MavenProject parent, Object propValue) throws EnforcerRuleException { final StringBuilder parentHierarchy = new StringBuilder("project."); MavenProject needle = project; @@ -115,7 +128,7 @@ void checkAgainstParentValue( needle = needle.getParent(); } final String propertyNameInParent = property.replace("project.", parentHierarchy.toString()); - Object parentValue = getPropertyValue(helper, propertyNameInParent); + Object parentValue = getPropertyValue(propertyNameInParent); if (propValue.equals(parentValue)) { final String errorMessage = createResultingErrorMessage(String.format( "Property '%s' evaluates to '%s'. This does match '%s' from parent %s", @@ -127,7 +140,6 @@ void checkAgainstParentValue( /** * Checks the value of the project against the given regex. * - * * @param propValue * @throws EnforcerRuleException */ @@ -194,8 +206,8 @@ final boolean isDefiningProject(final List rulesFromModel, final Xpp3Do * * @return configuration name. */ - final String getRuleName() { - return ruleName; + static final String getRuleName() { + return RULE_NAME; } /** @@ -247,10 +259,8 @@ List getRuleConfigurations(final Map plugins) { /** * Add the rules found in the given configuration to the list of rule configurations. * - * @param configuration - * configuration from which the rules are copied. May be null. - * @param ruleConfigurations - * List to which the rules will be added. + * @param configuration configuration from which the rules are copied. May be null. + * @param ruleConfigurations List to which the rules will be added. */ private void addRules(final Xpp3Dom configuration, final List ruleConfigurations) { // may be null when rules are defined in pluginManagement during invocation @@ -291,44 +301,25 @@ private List createRuleListWithNameSortedChildren(final List o /** * Extracted for easier testability. * - * @param helper * @return the value of the property. - * * @throws EnforcerRuleException */ - Object getPropertyValue(EnforcerRuleHelper helper) throws EnforcerRuleException { - return getPropertyValue(helper, property); + Object getPropertyValue() throws EnforcerRuleException { + return getPropertyValue(property); } /** * Extracted for easier testability. * - * @param helper * @param propertyName name of the property to extract. * @return the value of the property. * @throws EnforcerRuleException */ - Object getPropertyValue(EnforcerRuleHelper helper, final String propertyName) throws EnforcerRuleException { + Object getPropertyValue(final String propertyName) throws EnforcerRuleException { try { - return helper.evaluate("${" + propertyName + "}"); + return evaluator.evaluate("${" + propertyName + "}"); } catch (ExpressionEvaluationException eee) { - throw new EnforcerRuleException("Unable to evaluate property: " + propertyName, eee); - } - } - - /** - * Extracted for easier testability. - * - * @param helper - * @return the MavenProject enforcer is running on. - * - * @throws EnforcerRuleException - */ - MavenProject getMavenProject(EnforcerRuleHelper helper) throws EnforcerRuleException { - try { - return (MavenProject) helper.evaluate("${project}"); - } catch (ExpressionEvaluationException eee) { - throw new EnforcerRuleException("Unable to get project.", eee); + throw new EnforcerRuleError("Unable to evaluate property: " + propertyName, eee); } } @@ -362,6 +353,7 @@ String createResultingErrorMessage(String errorMessage) { } // HELPER methods for unittests. + /** * @param property the property to set */ @@ -389,11 +381,12 @@ void setMessage(String message) { private static class CreateInvokingRuleDom { private final Xpp3Dom ruleDom; + private final SortedMap map = new TreeMap<>(); /** Real work is done in the constructor */ CreateInvokingRuleDom(RequirePropertyDiverges rule) { - ruleDom = new Xpp3Dom(rule.getRuleName()); + ruleDom = new Xpp3Dom(getRuleName()); addToMapWhenNotNull(rule.property, "property"); addToMapWhenNotNull(rule.message, "message"); addToMapWhenNotNull(rule.regex, "regex"); @@ -423,27 +416,4 @@ private void addChildrenToRuleDom() { } } } - - // ********************* - - /** - * {@inheritDoc} - */ - public String getCacheId() { - return "0"; - } - - /** - * {@inheritDoc} - */ - public boolean isCacheable() { - return false; - } - - /** - * {@inheritDoc} - */ - public boolean isResultValid(EnforcerRule cachedRule) { - return false; - } } diff --git a/src/test/java/org/apache/maven/plugins/enforcer/RequireEncodingTest.java b/src/test/java/org/apache/maven/plugins/enforcer/RequireEncodingTest.java deleted file mode 100644 index d908ce79..00000000 --- a/src/test/java/org/apache/maven/plugins/enforcer/RequireEncodingTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.apache.maven.plugins.enforcer; - -import java.io.File; - -import org.apache.maven.enforcer.rule.api.EnforcerRuleException; -import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; -import org.apache.maven.plugin.logging.Log; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertThrows; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class RequireEncodingTest { - - private EnforcerRuleHelper helper; - private RequireEncoding rule; - - @Before - public void initFields() { - helper = mock(EnforcerRuleHelper.class); - rule = new RequireEncoding(); - } - - @Test - public void failUTF8() throws Exception { - - when(helper.evaluate("${basedir}")).thenReturn(new File("src/test/resources").getAbsolutePath()); - when(helper.evaluate("${project.build.sourceEncoding}")).thenReturn("UTF-8"); - when(helper.getLog()).thenReturn(mock(Log.class)); - - rule.setIncludes("ascii.txt"); - - assertThrows(EnforcerRuleException.class, () -> rule.execute(helper)); - } -} diff --git a/src/test/java/org/apache/maven/plugins/enforcer/ArtifactBuilder.java b/src/test/java/org/codehaus/mojo/extraenforcer/dependencies/ArtifactBuilder.java similarity index 98% rename from src/test/java/org/apache/maven/plugins/enforcer/ArtifactBuilder.java rename to src/test/java/org/codehaus/mojo/extraenforcer/dependencies/ArtifactBuilder.java index 8e5532ba..e113d538 100644 --- a/src/test/java/org/apache/maven/plugins/enforcer/ArtifactBuilder.java +++ b/src/test/java/org/codehaus/mojo/extraenforcer/dependencies/ArtifactBuilder.java @@ -1,4 +1,4 @@ -package org.apache.maven.plugins.enforcer; +package org.codehaus.mojo.extraenforcer.dependencies; /* * Licensed to the Apache Software Foundation (ASF) under one diff --git a/src/test/java/org/apache/maven/plugins/enforcer/ClassFileHelper.java b/src/test/java/org/codehaus/mojo/extraenforcer/dependencies/ClassFileHelper.java similarity index 98% rename from src/test/java/org/apache/maven/plugins/enforcer/ClassFileHelper.java rename to src/test/java/org/codehaus/mojo/extraenforcer/dependencies/ClassFileHelper.java index e7972ff6..18326dc9 100644 --- a/src/test/java/org/apache/maven/plugins/enforcer/ClassFileHelper.java +++ b/src/test/java/org/codehaus/mojo/extraenforcer/dependencies/ClassFileHelper.java @@ -1,4 +1,4 @@ -package org.apache.maven.plugins.enforcer; +package org.codehaus.mojo.extraenforcer.dependencies; /* * Licensed to the Apache Software Foundation (ASF) under one diff --git a/src/test/java/org/apache/maven/plugins/enforcer/ClassFileTest.java b/src/test/java/org/codehaus/mojo/extraenforcer/dependencies/ClassFileTest.java similarity index 95% rename from src/test/java/org/apache/maven/plugins/enforcer/ClassFileTest.java rename to src/test/java/org/codehaus/mojo/extraenforcer/dependencies/ClassFileTest.java index dd11bd01..b375b244 100644 --- a/src/test/java/org/apache/maven/plugins/enforcer/ClassFileTest.java +++ b/src/test/java/org/codehaus/mojo/extraenforcer/dependencies/ClassFileTest.java @@ -1,4 +1,4 @@ -package org.apache.maven.plugins.enforcer; +package org.codehaus.mojo.extraenforcer.dependencies; import org.junit.Rule; import org.junit.Test; diff --git a/src/test/java/org/apache/maven/plugins/enforcer/ClassesWithSameNameTest.java b/src/test/java/org/codehaus/mojo/extraenforcer/dependencies/ClassesWithSameNameTest.java similarity index 97% rename from src/test/java/org/apache/maven/plugins/enforcer/ClassesWithSameNameTest.java rename to src/test/java/org/codehaus/mojo/extraenforcer/dependencies/ClassesWithSameNameTest.java index 5b2dda5e..862db405 100644 --- a/src/test/java/org/apache/maven/plugins/enforcer/ClassesWithSameNameTest.java +++ b/src/test/java/org/codehaus/mojo/extraenforcer/dependencies/ClassesWithSameNameTest.java @@ -1,4 +1,4 @@ -package org.apache.maven.plugins.enforcer; +package org.codehaus.mojo.extraenforcer.dependencies; /* * Licensed to the Apache Software Foundation (ASF) under one @@ -22,9 +22,7 @@ import java.util.Set; import org.apache.maven.artifact.Artifact; -import org.apache.maven.monitor.logging.DefaultLog; -import org.apache.maven.plugin.logging.Log; -import org.codehaus.plexus.logging.console.ConsoleLogger; +import org.apache.maven.enforcer.rule.api.EnforcerLogger; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -33,6 +31,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; public class ClassesWithSameNameTest { /** logging thresholds are: DEBUG=0, INFO=1, WARNING=2, ERROR=3, FATAL ERROR=4, DISABLED=5 */ @@ -47,7 +46,7 @@ public class ClassesWithSameNameTest { /** this is an alias to make the code read better */ private static final boolean DETERMINE_DUPLICATES_BY_NAME = false; - private static final Log LOG = new DefaultLog(new ConsoleLogger(LOGGING_THRESHOLD, "test")); + private static final EnforcerLogger LOG = mock(EnforcerLogger.class); @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); diff --git a/src/test/java/org/apache/maven/plugins/enforcer/EnforceBytecodeVersionTest.java b/src/test/java/org/codehaus/mojo/extraenforcer/dependencies/EnforceBytecodeVersionTest.java similarity index 95% rename from src/test/java/org/apache/maven/plugins/enforcer/EnforceBytecodeVersionTest.java rename to src/test/java/org/codehaus/mojo/extraenforcer/dependencies/EnforceBytecodeVersionTest.java index ab038713..7fa6bd10 100644 --- a/src/test/java/org/apache/maven/plugins/enforcer/EnforceBytecodeVersionTest.java +++ b/src/test/java/org/codehaus/mojo/extraenforcer/dependencies/EnforceBytecodeVersionTest.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.apache.maven.plugins.enforcer; +package org.codehaus.mojo.extraenforcer.dependencies; import org.junit.Test; diff --git a/src/test/java/org/apache/maven/plugins/enforcer/JarUtilsTest.java b/src/test/java/org/codehaus/mojo/extraenforcer/dependencies/JarUtilsTest.java similarity index 89% rename from src/test/java/org/apache/maven/plugins/enforcer/JarUtilsTest.java rename to src/test/java/org/codehaus/mojo/extraenforcer/dependencies/JarUtilsTest.java index 79a3dec1..719eb62a 100644 --- a/src/test/java/org/apache/maven/plugins/enforcer/JarUtilsTest.java +++ b/src/test/java/org/codehaus/mojo/extraenforcer/dependencies/JarUtilsTest.java @@ -1,9 +1,9 @@ -package org.apache.maven.plugins.enforcer; +package org.codehaus.mojo.extraenforcer.dependencies; import org.apache.maven.artifact.Artifact; import org.junit.Test; -import static org.apache.maven.plugins.enforcer.ArtifactBuilder.newBuilder; +import static org.codehaus.mojo.extraenforcer.dependencies.ArtifactBuilder.newBuilder; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; diff --git a/src/test/java/org/codehaus/mojo/extraenforcer/encoding/RequireEncodingTest.java b/src/test/java/org/codehaus/mojo/extraenforcer/encoding/RequireEncodingTest.java new file mode 100644 index 00000000..356be29d --- /dev/null +++ b/src/test/java/org/codehaus/mojo/extraenforcer/encoding/RequireEncodingTest.java @@ -0,0 +1,42 @@ +package org.codehaus.mojo.extraenforcer.encoding; + +import java.io.File; +import java.util.Properties; + +import org.apache.maven.enforcer.rule.api.EnforcerLogger; +import org.apache.maven.enforcer.rule.api.EnforcerRuleException; +import org.apache.maven.project.MavenProject; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class RequireEncodingTest { + + private RequireEncoding rule; + + private MavenProject project; + + @Before + public void initFields() { + project = mock(MavenProject.class); + rule = new RequireEncoding(project); + rule.setLog(mock(EnforcerLogger.class)); + } + + @Test + public void failUTF8() throws Exception { + + when(project.getBasedir()).thenReturn(new File("src/test/resources").getAbsoluteFile()); + + Properties properties = new Properties(); + properties.put("project.build.sourceEncoding", "UTF-8"); + when(project.getProperties()).thenReturn(properties); + + rule.setIncludes("ascii.txt"); + + assertThrows(EnforcerRuleException.class, () -> rule.execute()); + } +} diff --git a/src/test/java/org/codehaus/mojo/extraenforcerrules/it/BanDuplicateClassesLogParser.java b/src/test/java/org/codehaus/mojo/extraenforcer/it/BanDuplicateClassesLogParser.java similarity index 95% rename from src/test/java/org/codehaus/mojo/extraenforcerrules/it/BanDuplicateClassesLogParser.java rename to src/test/java/org/codehaus/mojo/extraenforcer/it/BanDuplicateClassesLogParser.java index c8ab6a45..01d9d07b 100644 --- a/src/test/java/org/codehaus/mojo/extraenforcerrules/it/BanDuplicateClassesLogParser.java +++ b/src/test/java/org/codehaus/mojo/extraenforcer/it/BanDuplicateClassesLogParser.java @@ -1,4 +1,4 @@ -package org.codehaus.mojo.extraenforcerrules.it; +package org.codehaus.mojo.extraenforcer.it; /* * Licensed to the Apache Software Foundation (ASF) under one @@ -33,7 +33,7 @@ */ public class BanDuplicateClassesLogParser { private static final String DUPLICATE_START_LINE = - "[ERROR] Rule 0: org.apache.maven.plugins.enforcer.BanDuplicateClasses failed with message:"; + "[ERROR] Rule 0: org.codehaus.mojo.extraenforcer.dependencies.BanDuplicateClasses failed with message:"; private final File logFile; diff --git a/src/test/java/org/codehaus/mojo/extraenforcerrules/it/package-info.java b/src/test/java/org/codehaus/mojo/extraenforcer/it/package-info.java similarity index 95% rename from src/test/java/org/codehaus/mojo/extraenforcerrules/it/package-info.java rename to src/test/java/org/codehaus/mojo/extraenforcer/it/package-info.java index eb5078a4..b84d862d 100644 --- a/src/test/java/org/codehaus/mojo/extraenforcerrules/it/package-info.java +++ b/src/test/java/org/codehaus/mojo/extraenforcer/it/package-info.java @@ -2,7 +2,7 @@ * Utility classes for use in * integration tests. */ -package org.codehaus.mojo.extraenforcerrules.it; +package org.codehaus.mojo.extraenforcer.it; /* * Licensed to the Apache Software Foundation (ASF) under one diff --git a/src/test/java/org/apache/maven/plugins/enforcer/AbstractRequireRolesTest.java b/src/test/java/org/codehaus/mojo/extraenforcer/model/AbstractRequireRolesTest.java similarity index 97% rename from src/test/java/org/apache/maven/plugins/enforcer/AbstractRequireRolesTest.java rename to src/test/java/org/codehaus/mojo/extraenforcer/model/AbstractRequireRolesTest.java index 29316ff7..40de1f42 100644 --- a/src/test/java/org/apache/maven/plugins/enforcer/AbstractRequireRolesTest.java +++ b/src/test/java/org/codehaus/mojo/extraenforcer/model/AbstractRequireRolesTest.java @@ -1,4 +1,4 @@ -package org.apache.maven.plugins.enforcer; +package org.codehaus.mojo.extraenforcer.model; /* * Licensed to the Apache Software Foundation (ASF) under one diff --git a/src/test/java/org/apache/maven/plugins/enforcer/RequirePropertyDivergesTest.java b/src/test/java/org/codehaus/mojo/extraenforcer/model/RequirePropertyDivergesTest.java similarity index 80% rename from src/test/java/org/apache/maven/plugins/enforcer/RequirePropertyDivergesTest.java rename to src/test/java/org/codehaus/mojo/extraenforcer/model/RequirePropertyDivergesTest.java index 2b3cd6b9..31b02fea 100644 --- a/src/test/java/org/apache/maven/plugins/enforcer/RequirePropertyDivergesTest.java +++ b/src/test/java/org/codehaus/mojo/extraenforcer/model/RequirePropertyDivergesTest.java @@ -1,4 +1,4 @@ -package org.apache.maven.plugins.enforcer; +package org.codehaus.mojo.extraenforcer.model; /* * Licensed to the Apache Software Foundation (ASF) under one @@ -19,18 +19,21 @@ * under the License. */ +import org.apache.maven.enforcer.rule.api.EnforcerLogger; import org.apache.maven.enforcer.rule.api.EnforcerRuleException; -import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; import org.apache.maven.model.Build; import org.apache.maven.model.Model; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; import org.apache.maven.model.PluginManagement; -import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; +import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; @@ -39,23 +42,24 @@ /** * @author mirko */ +@RunWith(MockitoJUnitRunner.class) public class RequirePropertyDivergesTest { - final EnforcerRuleHelper helper = mock(EnforcerRuleHelper.class); - - final RequirePropertyDiverges instance = new RequirePropertyDiverges(); + @Mock + private ExpressionEvaluator evaluator; /** * Test of execute method, of class RequirePropertyDiverges. */ @Test public void testExecuteInChild() throws EnforcerRuleException { - RequirePropertyDiverges mockInstance = createMockRule(); final MavenProject project = createMavenProject("company", "child"); final MavenProject parent = createParentProject(); project.setParent(parent); + + RequirePropertyDiverges mockInstance = createMockRule(project); setUpHelper(project, "childValue"); - mockInstance.execute(helper); + mockInstance.execute(); } /** @@ -63,10 +67,10 @@ public void testExecuteInChild() throws EnforcerRuleException { */ @Test public void testExecuteInParent() throws EnforcerRuleException { - RequirePropertyDiverges mockInstance = createMockRule(); final MavenProject project = createParentProject(); + RequirePropertyDiverges mockInstance = createMockRule(project); setUpHelper(project, "parentValue"); - mockInstance.execute(helper); + mockInstance.execute(); } private MavenProject createParentProject() { @@ -86,8 +90,8 @@ private MavenProject createParentProject() { */ @Test public void testExecuteInParentWithConfigurationInPluginManagement() throws EnforcerRuleException { - RequirePropertyDiverges mockInstance = createMockRule(); final MavenProject project = createMavenProject("company", "company-parent-pom"); + RequirePropertyDiverges mockInstance = createMockRule(project); final Build build = new Build(); // create pluginManagement final Plugin pluginInManagement = newPlugin("org.apache.maven.plugins", "maven-enforcer-plugin", "1.0"); @@ -103,7 +107,7 @@ public void testExecuteInParentWithConfigurationInPluginManagement() throws Enfo project.getOriginalModel().setBuild(build); // project.getOriginalModel().setBuild( build ); setUpHelper(project, "parentValue"); - mockInstance.execute(helper); + mockInstance.execute(); } /** @@ -111,8 +115,8 @@ public void testExecuteInParentWithConfigurationInPluginManagement() throws Enfo */ @Test public void testExecuteInParentWithConfigurationInExecution() throws EnforcerRuleException { - RequirePropertyDiverges mockInstance = createMockRule(); final MavenProject project = createMavenProject("company", "company-parent-pom"); + RequirePropertyDiverges mockInstance = createMockRule(project); final Build build = new Build(); build.setPluginManagement(new PluginManagement()); final Plugin plugin = newPlugin("org.apache.maven.plugins", "maven-enforcer-plugin", "1.0"); @@ -123,12 +127,14 @@ public void testExecuteInParentWithConfigurationInExecution() throws EnforcerRul build.addPlugin(plugin); project.getOriginalModel().setBuild(build); setUpHelper(project, "parentValue"); - mockInstance.execute(helper); + mockInstance.execute(); } @Test public void testProjectWithoutEnforcer() { final Build build = new Build(); + RequirePropertyDiverges instance = createMockRule(mock(MavenProject.class)); + // build.setPluginManagement( new PluginManagement() ); instance.getRuleConfigurations(build); } @@ -138,12 +144,12 @@ public void testProjectWithoutEnforcer() { */ @Test(expected = EnforcerRuleException.class) public void testExecuteInChildShouldFail() throws EnforcerRuleException { - RequirePropertyDiverges mockInstance = createMockRule(); final MavenProject project = createMavenProject("company", "child"); + RequirePropertyDiverges mockInstance = createMockRule(project); final MavenProject parent = createParentProject(); project.setParent(parent); setUpHelper(project, "parentValue"); - mockInstance.execute(helper); + mockInstance.execute(); } /** @@ -151,6 +157,7 @@ public void testExecuteInChildShouldFail() throws EnforcerRuleException { */ @Test public void testCheckPropValueNotBlank() throws Exception { + RequirePropertyDiverges instance = createMockRule(mock(MavenProject.class)); instance.setProperty("checkedProperty"); instance.checkPropValueNotBlank("propertyValue"); } @@ -160,12 +167,14 @@ public void testCheckPropValueNotBlank() throws Exception { */ @Test(expected = EnforcerRuleException.class) public void testCheckPropValueNotBlankNull() throws EnforcerRuleException { + RequirePropertyDiverges instance = createMockRule(mock(MavenProject.class)); instance.setProperty("checkedProperty"); instance.checkPropValueNotBlank(null); } @Test public void testCreateResultingErrorMessageReturningCustomMessage() { + RequirePropertyDiverges instance = createMockRule(mock(MavenProject.class)); instance.setProperty("checkedProperty"); instance.setMessage("This is needed for foo."); final String actual = instance.createResultingErrorMessage("default message"); @@ -175,6 +184,8 @@ public void testCreateResultingErrorMessageReturningCustomMessage() { @Test public void testCreateResultingErrorMessageReturningDefaultMessage() { + RequirePropertyDiverges instance = createMockRule(mock(MavenProject.class)); + instance.setProperty("checkedProperty"); instance.setMessage(null); String actual = instance.createResultingErrorMessage("default message"); @@ -189,20 +200,16 @@ public void testCreateResultingErrorMessageReturningDefaultMessage() { @Test public void testGetRuleName() { - assertEquals("requirePropertyDiverges", instance.getRuleName()); + assertEquals("requirePropertyDiverges", RequirePropertyDiverges.getRuleName()); } @Test(expected = EnforcerRuleException.class) public void testGetPropertyValueFail() throws ExpressionEvaluationException, EnforcerRuleException { - when(helper.evaluate("${checkedProperty}")).thenThrow(ExpressionEvaluationException.class); - instance.setProperty("checkedProperty"); - instance.getPropertyValue(helper); - } + RequirePropertyDiverges instance = createMockRule(mock(MavenProject.class)); - @Test(expected = EnforcerRuleException.class) - public void testGetProjectFail() throws ExpressionEvaluationException, EnforcerRuleException { - when(helper.evaluate("${project}")).thenThrow(ExpressionEvaluationException.class); - instance.getMavenProject(helper); + when(evaluator.evaluate("${checkedProperty}")).thenThrow(ExpressionEvaluationException.class); + instance.setProperty("checkedProperty"); + instance.getPropertyValue(); } @Test(expected = EnforcerRuleException.class) @@ -217,18 +224,21 @@ public void testCheckAgainstParentValue() throws EnforcerRuleException, Expressi void testCheckAgainstParentValue(final String parentGroupId, final String childGroupId) throws ExpressionEvaluationException, EnforcerRuleException { + MavenProject project = createMavenProject(childGroupId, "child"); + RequirePropertyDiverges instance = createMockRule(project); + instance.setProperty("project.groupId"); MavenProject parent = createMavenProject(parentGroupId, "parent-pom"); - MavenProject project = createMavenProject(childGroupId, "child"); project.setParent(parent); - when(helper.evaluate("${project.parent.groupId}")).thenReturn(parentGroupId); - instance.checkAgainstParentValue(project, parent, helper, childGroupId); + when(evaluator.evaluate("${project.parent.groupId}")).thenReturn(parentGroupId); + instance.checkAgainstParentValue(project, parent, childGroupId); } - static RequirePropertyDiverges createMockRule() { - RequirePropertyDiverges instance = new RequirePropertyDiverges(); + private RequirePropertyDiverges createMockRule(MavenProject project) { + RequirePropertyDiverges instance = new RequirePropertyDiverges(project, evaluator); instance.setRegex("parentValue"); instance.setProperty("checkedProperty"); + instance.setLog(mock(EnforcerLogger.class)); return instance; } @@ -241,19 +251,18 @@ static MavenProject createMavenProject(final String groupId, final String artifa } void setUpHelper(final MavenProject project, final String propertyValue) throws RuntimeException { + // when(helper.evaluate("${project}")).thenReturn(project); try { - when(helper.evaluate("${project}")).thenReturn(project); - when(helper.evaluate("${checkedProperty}")).thenReturn(propertyValue); - } catch (ExpressionEvaluationException ex) { - throw new RuntimeException(ex); + when(evaluator.evaluate("${checkedProperty}")).thenReturn(propertyValue); + } catch (ExpressionEvaluationException e) { + throw new RuntimeException(e); } - when(helper.getLog()).thenReturn(mock(Log.class)); } Xpp3Dom createPluginConfiguration() { final Xpp3Dom configuration = new Xpp3Dom("configuration"); final Xpp3Dom rules = new Xpp3Dom("rules"); - final Xpp3Dom rule = new Xpp3Dom(instance.getRuleName()); + final Xpp3Dom rule = new Xpp3Dom(RequirePropertyDiverges.getRuleName()); rules.addChild(rule); final Xpp3Dom property = new Xpp3Dom("property"); property.setValue("checkedProperty"); diff --git a/src/test/java/org/apache/maven/plugins/enforcer/RequireRolesTest.java b/src/test/java/org/codehaus/mojo/extraenforcer/model/RequireRolesTest.java similarity index 90% rename from src/test/java/org/apache/maven/plugins/enforcer/RequireRolesTest.java rename to src/test/java/org/codehaus/mojo/extraenforcer/model/RequireRolesTest.java index c0a17d46..0267b8b5 100644 --- a/src/test/java/org/apache/maven/plugins/enforcer/RequireRolesTest.java +++ b/src/test/java/org/codehaus/mojo/extraenforcer/model/RequireRolesTest.java @@ -1,4 +1,4 @@ -package org.apache.maven.plugins.enforcer; +package org.codehaus.mojo.extraenforcer.model; /* * Licensed to the Apache Software Foundation (ASF) under one @@ -18,6 +18,7 @@ * specific language governing permissions and limitations * under the License. */ + import java.util.Arrays; import java.util.Collections; import java.util.HashSet; @@ -25,12 +26,10 @@ import java.util.Set; import org.apache.maven.enforcer.rule.api.EnforcerRuleException; -import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; import org.apache.maven.model.Contributor; import org.apache.maven.model.Developer; import org.apache.maven.project.MavenProject; import org.junit.Test; -import org.mockito.Mockito; import static org.junit.Assert.assertEquals; @@ -40,51 +39,51 @@ */ public class RequireRolesTest { - final EnforcerRuleHelper helper = Mockito.mock(EnforcerRuleHelper.class); + private MavenProject mavenProject; @Test public void shouldSucceedBecauseArchitectAsDeveloperAndBusinessEngineerAsContributorArePresent() throws Exception { addProjectHavingAnArchitectAsDeveloperAndABusinessEngineerAsContributorToHelper(); newRequireDeveloperRoles("architect" /*required role*/, null /* valid roles not needed */) - .execute(helper); + .execute(); newRequireContributorRoles("business engineer" /*required role*/, "*" /* valid roles */) - .execute(helper); + .execute(); } @Test(expected = EnforcerRuleException.class) public void shouldFailBecauseContributorWithRoleQualityManagerIsMissing() throws Exception { addProjectHavingAnArchitectAsDeveloperAndABusinessEngineerAsContributorToHelper(); - newRequireContributorRoles("business engineer, quality manager", null).execute(helper); + newRequireContributorRoles("business engineer, quality manager", null).execute(); } @Test(expected = EnforcerRuleException.class) public void shouldFailBecauseDeveloperWithRoleCodeMonkeyIsMissing() throws Exception { addProjectHavingAnArchitectAsDeveloperAndABusinessEngineerAsContributorToHelper(); newRequireDeveloperRoles("codemonkey" /* required but not in project */, null) - .execute(helper); + .execute(); } @Test(expected = EnforcerRuleException.class) public void shouldFailBecauseContributorRoleBusinessEngineerIsInvalid() throws Exception { addProjectHavingAnArchitectAsDeveloperAndABusinessEngineerAsContributorToHelper(); newRequireContributorRoles(null /* no required roles needed */, "hacker" /* only valid role */) - .execute(helper); + .execute(); } @Test(expected = EnforcerRuleException.class) public void shouldFailBecauseNoContributorRolesAtAllAreValid() throws Exception { addProjectHavingAnArchitectAsDeveloperAndABusinessEngineerAsContributorToHelper(); newRequireContributorRoles(null /* no required roles needed */, "" /*but no role is valid at all */) - .execute(helper); + .execute(); } @Test public void shouldSucceedAsNoRolesAreRequiredAndAllAreAccepted() throws Exception { addProjectHavingAnArchitectAsDeveloperAndABusinessEngineerAsContributorToHelper(); newRequireContributorRoles(null /* no required roles */, "*" /* any role is valid */) - .execute(helper); + .execute(); newRequireContributorRoles(null /* no required roles */, null /* any role is valid */) - .execute(helper); + .execute(); } /** @@ -93,7 +92,7 @@ public void shouldSucceedAsNoRolesAreRequiredAndAllAreAccepted() throws Exceptio @Test public void testGetRolesFromString() { HashSet expResult = new HashSet<>(Arrays.asList("architect", "codemonkey", "business engineer")); - final RequireContributorRoles sut = new RequireContributorRoles(); + final RequireContributorRoles sut = new RequireContributorRoles(mavenProject); Set result = sut.getRolesFromString(" architect, business engineer , codemonkey "); assertEquals(expResult, result); } @@ -120,19 +119,18 @@ public void testGetRolesFromMaven() { } private void addProjectHavingAnArchitectAsDeveloperAndABusinessEngineerAsContributorToHelper() throws Exception { - final MavenProject mavenProject = new MavenProject(); + mavenProject = new MavenProject(); final Developer developer = new Developer(); developer.addRole("architect"); mavenProject.addDeveloper(developer); final Contributor contributor = new Contributor(); contributor.addRole("business engineer"); mavenProject.addContributor(contributor); - Mockito.when(helper.evaluate("${project}")).thenReturn(mavenProject); } private RequireDeveloperRoles newRequireDeveloperRoles( final String commaSeparatedRequiredRoles, final String commaSeparatedValidRoles) { - final RequireDeveloperRoles sut = new RequireDeveloperRoles(); + final RequireDeveloperRoles sut = new RequireDeveloperRoles(mavenProject); if (commaSeparatedRequiredRoles != null) { sut.setRequiredRoles(commaSeparatedRequiredRoles); } @@ -145,7 +143,7 @@ private RequireDeveloperRoles newRequireDeveloperRoles( private RequireContributorRoles newRequireContributorRoles( final String commaSeparatedRequiredRoles, final String commaSeparatedValidRoles) { - final RequireContributorRoles sut = new RequireContributorRoles(); + final RequireContributorRoles sut = new RequireContributorRoles(mavenProject); if (commaSeparatedRequiredRoles != null) { sut.setRequiredRoles(commaSeparatedRequiredRoles); } diff --git a/src/test/java/org/apache/maven/plugins/enforcer/RuleXpp3DomTest.java b/src/test/java/org/codehaus/mojo/extraenforcer/model/RuleXpp3DomTest.java similarity index 81% rename from src/test/java/org/apache/maven/plugins/enforcer/RuleXpp3DomTest.java rename to src/test/java/org/codehaus/mojo/extraenforcer/model/RuleXpp3DomTest.java index c6a01456..137edcfb 100644 --- a/src/test/java/org/apache/maven/plugins/enforcer/RuleXpp3DomTest.java +++ b/src/test/java/org/codehaus/mojo/extraenforcer/model/RuleXpp3DomTest.java @@ -1,4 +1,4 @@ -package org.apache.maven.plugins.enforcer; +package org.codehaus.mojo.extraenforcer.model; /* * Licensed to the Apache Software Foundation (ASF) under one @@ -19,8 +19,14 @@ * under the License. */ +import org.apache.maven.project.MavenProject; +import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; @@ -29,10 +35,20 @@ * * @author mfriedenhagen */ +@RunWith(MockitoJUnitRunner.class) public class RuleXpp3DomTest { - final RequirePropertyDiverges sut1 = new RequirePropertyDiverges(); - final RequirePropertyDiverges sut2 = new RequirePropertyDiverges(); + @Mock + private MavenProject project; + + @Mock + private ExpressionEvaluator evaluator; + + @InjectMocks + private RequirePropertyDiverges sut1; + + @InjectMocks + private RequirePropertyDiverges sut2; @Test public void checkRuleWithoutRegex() {