diff --git a/enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/BanTransitiveDependencies.java b/enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/dependency/BanTransitiveDependencies.java similarity index 86% rename from enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/BanTransitiveDependencies.java rename to enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/dependency/BanTransitiveDependencies.java index 7d96582a..212d3e4d 100644 --- a/enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/BanTransitiveDependencies.java +++ b/enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/dependency/BanTransitiveDependencies.java @@ -16,21 +16,23 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.maven.plugins.enforcer; +package org.apache.maven.enforcer.rules.dependency; + +import javax.inject.Inject; +import javax.inject.Named; import java.util.List; +import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import org.apache.maven.RepositoryUtils; -import org.apache.maven.enforcer.rule.api.EnforcerRule; import org.apache.maven.enforcer.rule.api.EnforcerRuleException; -import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; +import org.apache.maven.enforcer.rules.AbstractStandardEnforcerRule; import org.apache.maven.enforcer.rules.utils.ArtifactMatcher; import org.apache.maven.enforcer.rules.utils.ArtifactUtils; import org.apache.maven.execution.MavenSession; -import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; import org.eclipse.aether.artifact.ArtifactTypeRegistry; import org.eclipse.aether.graph.Dependency; import org.eclipse.aether.graph.DependencyNode; @@ -43,7 +45,8 @@ * * @author Jakub Senko */ -public class BanTransitiveDependencies extends AbstractNonCacheableEnforcerRule implements EnforcerRule { +@Named("banTransitiveDependencies") +public final class BanTransitiveDependencies extends AbstractStandardEnforcerRule { /** * Specify the dependencies that will be ignored. This can be a list of artifacts in the format @@ -63,6 +66,16 @@ public class BanTransitiveDependencies extends AbstractNonCacheableEnforcerRule */ private List includes; + private final MavenSession session; + + private final ResolveUtil resolveUtil; + + @Inject + public BanTransitiveDependencies(MavenSession session, ResolveUtil resolveUtil) { + this.session = Objects.requireNonNull(session); + this.resolveUtil = Objects.requireNonNull(resolveUtil); + } + /** * Searches dependency tree recursively for transitive dependencies that are not excluded, while generating nice * info message along the way. @@ -126,13 +139,7 @@ private static boolean searchTree( } @Override - public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { - MavenSession session; - try { - session = (MavenSession) helper.evaluate("${session}"); - } catch (ExpressionEvaluationException e) { - throw new RuntimeException(e); - } + public void execute() throws EnforcerRuleException { ArtifactTypeRegistry artifactTypeRegistry = session.getRepositorySession().getArtifactTypeRegistry(); ArtifactMatcher exclusions = new ArtifactMatcher(excludes, includes); @@ -140,10 +147,15 @@ public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { .map(d -> RepositoryUtils.toDependency(d, artifactTypeRegistry)) .collect(Collectors.toSet()); - DependencyNode rootNode = ArtifactUtils.resolveTransitiveDependencies(helper); + DependencyNode rootNode = resolveUtil.resolveTransitiveDependencies(); StringBuilder generatedMessage = new StringBuilder(); if (searchTree(rootNode, 0, exclusions, directDependencies, generatedMessage)) { throw new EnforcerRuleException(ofNullable(getMessage()).orElse(generatedMessage.toString())); } } + + @Override + public String toString() { + return String.format("BanTransitiveDependencies[message=%s, excludes=%s]", getMessage(), excludes); + } } diff --git a/enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/BannedDependencies.java b/enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/dependency/BannedDependencies.java similarity index 66% rename from enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/BannedDependencies.java rename to enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/dependency/BannedDependencies.java index 6d6596d0..77d2e17b 100644 --- a/enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/BannedDependencies.java +++ b/enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/dependency/BannedDependencies.java @@ -16,25 +16,43 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.maven.plugins.enforcer; +package org.apache.maven.enforcer.rules.dependency; + +import javax.inject.Inject; +import javax.inject.Named; import org.apache.maven.artifact.Artifact; import org.apache.maven.enforcer.rules.utils.ArtifactUtils; +import org.apache.maven.execution.MavenSession; /** * This rule checks that lists of dependencies are not included. * * @author Brian Fox */ -public class BannedDependencies extends BannedDependenciesBase { +@Named("bannedDependencies") +public final class BannedDependencies extends BannedDependenciesBase { + + @Inject + BannedDependencies(MavenSession session, ResolveUtil resolveUtil) { + super(session, resolveUtil); + } + @Override protected boolean validate(Artifact artifact) { - return !ArtifactUtils.matchDependencyArtifact(artifact, excludes) - || ArtifactUtils.matchDependencyArtifact(artifact, includes); + return !ArtifactUtils.matchDependencyArtifact(artifact, getExcludes()) + || ArtifactUtils.matchDependencyArtifact(artifact, getIncludes()); } @Override protected String getErrorMessage() { return "banned via the exclude/include list"; } + + @Override + public String toString() { + return String.format( + "BannedDependencies[message=%s, excludes=%s, includes=%s, searchTransitive=%b]", + getMessage(), getExcludes(), getIncludes(), isSearchTransitive()); + } } diff --git a/enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/BannedDependenciesBase.java b/enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/dependency/BannedDependenciesBase.java similarity index 82% rename from enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/BannedDependenciesBase.java rename to enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/dependency/BannedDependenciesBase.java index e7776aca..4ee240e5 100644 --- a/enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/BannedDependenciesBase.java +++ b/enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/dependency/BannedDependenciesBase.java @@ -16,17 +16,17 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.maven.plugins.enforcer; +package org.apache.maven.enforcer.rules.dependency; import java.util.List; +import java.util.Objects; import org.apache.commons.lang3.StringUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.enforcer.rule.api.EnforcerRuleException; -import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; +import org.apache.maven.enforcer.rules.AbstractStandardEnforcerRule; import org.apache.maven.enforcer.rules.utils.ArtifactUtils; import org.apache.maven.execution.MavenSession; -import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; import org.eclipse.aether.graph.DependencyNode; /** @@ -34,7 +34,7 @@ * dependency tree by traversing all children and validating every * dependency artifact. */ -abstract class BannedDependenciesBase extends AbstractNonCacheableEnforcerRule { +abstract class BannedDependenciesBase extends AbstractStandardEnforcerRule { /** * Specify the banned dependencies. This can be a list of artifacts in the format @@ -46,7 +46,7 @@ abstract class BannedDependenciesBase extends AbstractNonCacheableEnforcerRule { * @see #setExcludes(List) * @see #getExcludes() */ - protected List excludes = null; + private List excludes = null; /** * Specify the allowed dependencies. This can be a list of artifacts in the format @@ -60,19 +60,26 @@ abstract class BannedDependenciesBase extends AbstractNonCacheableEnforcerRule { * @see #setIncludes(List) * @see #getIncludes() */ - protected List includes = null; + private List includes = null; /** Specify if transitive dependencies should be searched (default) or only look at direct dependencies. */ private boolean searchTransitive = true; + private final MavenSession session; + + private final ResolveUtil resolveUtil; + + BannedDependenciesBase(MavenSession session, ResolveUtil resolveUtil) { + this.session = Objects.requireNonNull(session); + this.resolveUtil = Objects.requireNonNull(resolveUtil); + } + + protected MavenSession getSession() { + return session; + } + @Override - public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { - MavenSession session; - try { - session = (MavenSession) helper.evaluate("${session}"); - } catch (ExpressionEvaluationException e) { - throw new EnforcerRuleException("Cannot resolve MavenSession", e); - } + public void execute() throws EnforcerRuleException { if (!searchTransitive) { String result = session.getCurrentProject().getDependencyArtifacts().stream() @@ -80,19 +87,28 @@ public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { .collect( StringBuilder::new, (messageBuilder, node) -> messageBuilder + .append(System.lineSeparator()) .append(node.getId()) .append(" <--- ") .append(getErrorMessage()), (m1, m2) -> m1.append(m2.toString())) .toString(); if (!result.isEmpty()) { - throw new EnforcerRuleException(result); + String message = ""; + if (getMessage() != null) { + message = getMessage() + System.lineSeparator(); + } + throw new EnforcerRuleException(message + result); } } else { StringBuilder messageBuilder = new StringBuilder(); - DependencyNode rootNode = ArtifactUtils.resolveTransitiveDependencies(helper); + DependencyNode rootNode = resolveUtil.resolveTransitiveDependencies(); if (!validate(rootNode, 0, messageBuilder)) { - throw new EnforcerRuleException(messageBuilder.toString()); + String message = ""; + if (getMessage() != null) { + message = getMessage() + System.lineSeparator(); + } + throw new EnforcerRuleException(message + messageBuilder); } } } @@ -127,15 +143,6 @@ protected boolean validate(DependencyNode node, int level, StringBuilder message */ protected abstract boolean validate(Artifact dependency); - /** - * Checks if is search transitive. - * - * @return the searchTransitive - */ - public boolean isSearchTransitive() { - return this.searchTransitive; - } - /** * Sets the search transitive. * @@ -193,4 +200,8 @@ public List getIncludes() { public void setIncludes(List theIncludes) { this.includes = theIncludes; } + + public boolean isSearchTransitive() { + return searchTransitive; + } } diff --git a/enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/DependencyConvergence.java b/enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/dependency/DependencyConvergence.java similarity index 55% rename from enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/DependencyConvergence.java rename to enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/dependency/DependencyConvergence.java index 7d8503b6..eb583c7b 100644 --- a/enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/DependencyConvergence.java +++ b/enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/dependency/DependencyConvergence.java @@ -16,18 +16,19 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.maven.plugins.enforcer; +package org.apache.maven.enforcer.rules.dependency; + +import javax.inject.Inject; +import javax.inject.Named; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Objects; -import org.apache.maven.enforcer.rule.api.EnforcerRule; import org.apache.maven.enforcer.rule.api.EnforcerRuleException; -import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; +import org.apache.maven.enforcer.rules.AbstractStandardEnforcerRule; import org.apache.maven.enforcer.rules.utils.ArtifactUtils; -import org.apache.maven.enforcer.rules.utils.DependencyVersionMap; -import org.apache.maven.plugin.logging.Log; import org.eclipse.aether.collection.DependencyCollectionContext; import org.eclipse.aether.collection.DependencySelector; import org.eclipse.aether.graph.Dependency; @@ -40,8 +41,8 @@ /** * @author Rex Hoffman */ -public class DependencyConvergence implements EnforcerRule { - private static Log log; +@Named("dependencyConvergence") +public final class DependencyConvergence extends AbstractStandardEnforcerRule { private boolean uniqueVersions; @@ -51,51 +52,47 @@ public class DependencyConvergence implements EnforcerRule { private DependencyVersionMap dependencyVersionMap; - public void setUniqueVersions(boolean uniqueVersions) { - this.uniqueVersions = uniqueVersions; + private final ResolveUtil resolveUtil; + + @Inject + public DependencyConvergence(ResolveUtil resolveUtil) { + this.resolveUtil = Objects.requireNonNull(resolveUtil); } @Override - public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { - if (log == null) { - log = helper.getLog(); + public void execute() throws EnforcerRuleException { + + DependencyNode node = resolveUtil.resolveTransitiveDependencies( + // TODO: use a modified version of ExclusionDependencySelector to process excludes and includes + new DependencySelector() { + @Override + public boolean selectDependency(Dependency dependency) { + // regular OptionalDependencySelector only discriminates optional dependencies at level 2+ + return !dependency.isOptional() + // regular scope selectors only discard transitive dependencies + // and always allow direct dependencies + && !dependency.getScope().equals(SCOPE_TEST) + && !dependency.getScope().equals(SCOPE_PROVIDED); + } + + @Override + public DependencySelector deriveChildSelector(DependencyCollectionContext context) { + return this; + } + }, + // process dependency exclusions + new ExclusionDependencySelector()); + dependencyVersionMap = new DependencyVersionMap().setUniqueVersions(uniqueVersions); + node.accept(dependencyVersionMap); + + List errorMsgs = new ArrayList<>( + getConvergenceErrorMsgs(dependencyVersionMap.getConflictedVersionNumbers(includes, excludes))); + for (CharSequence errorMsg : errorMsgs) { + getLog().warnOrError(errorMsg); } - try { - DependencyNode node = ArtifactUtils.resolveTransitiveDependencies( - helper, - // TODO: use a modified version of ExclusionDependencySelector to process excludes and includes - new DependencySelector() { - @Override - public boolean selectDependency(Dependency dependency) { - // regular OptionalDependencySelector only discriminates optional dependencies at level 2+ - return !dependency.isOptional() - // regular scope selectors only discard transitive dependencies - // and always allow direct dependencies - && !dependency.getScope().equals(SCOPE_TEST) - && !dependency.getScope().equals(SCOPE_PROVIDED); - } - - @Override - public DependencySelector deriveChildSelector(DependencyCollectionContext context) { - return this; - } - }, - // process dependency exclusions - new ExclusionDependencySelector()); - dependencyVersionMap = new DependencyVersionMap(log).setUniqueVersions(uniqueVersions); - node.accept(dependencyVersionMap); - - List errorMsgs = new ArrayList<>( - getConvergenceErrorMsgs(dependencyVersionMap.getConflictedVersionNumbers(includes, excludes))); - for (CharSequence errorMsg : errorMsgs) { - log.warn(errorMsg); - } - if (errorMsgs.size() > 0) { - throw new EnforcerRuleException( - "Failed while enforcing releasability. " + "See above detailed error message."); - } - } catch (Exception e) { - throw new EnforcerRuleException(e.getLocalizedMessage(), e); + if (errorMsgs.size() > 0) { + throw new EnforcerRuleException( + "Failed while enforcing releasability. " + "See above detailed error message."); } } @@ -143,17 +140,9 @@ private String buildConvergenceErrorMsg(List nodeList) { } @Override - public String getCacheId() { - return ""; - } - - @Override - public boolean isCacheable() { - return false; - } - - @Override - public boolean isResultValid(EnforcerRule ignored) { - return false; + public String toString() { + return String.format( + "DependencyConvergence[includes=%s, excludes=%s, uniqueVersions=%b]", + includes, excludes, uniqueVersions); } } diff --git a/enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/utils/DependencyVersionMap.java b/enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/dependency/DependencyVersionMap.java similarity index 94% rename from enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/utils/DependencyVersionMap.java rename to enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/dependency/DependencyVersionMap.java index 01567fc4..29fcbbc6 100644 --- a/enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/utils/DependencyVersionMap.java +++ b/enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/dependency/DependencyVersionMap.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.maven.enforcer.rules.utils; +package org.apache.maven.enforcer.rules.dependency; import java.util.ArrayList; import java.util.HashMap; @@ -24,7 +24,9 @@ import java.util.Map; import org.apache.commons.lang3.StringUtils; -import org.apache.maven.plugin.logging.Log; +import org.apache.maven.enforcer.rules.utils.ArtifactUtils; +import org.apache.maven.enforcer.rules.utils.ParentNodeProvider; +import org.apache.maven.enforcer.rules.utils.ParentsVisitor; import org.eclipse.aether.artifact.Artifact; import org.eclipse.aether.graph.DependencyNode; import org.eclipse.aether.graph.DependencyVisitor; @@ -32,12 +34,12 @@ /** * @author Brian Fox */ -public class DependencyVersionMap implements DependencyVisitor, ParentNodeProvider { +class DependencyVersionMap implements DependencyVisitor, ParentNodeProvider { private ParentsVisitor parentsVisitor; private boolean uniqueVersions; private final Map> idsToNode = new HashMap<>(); - public DependencyVersionMap(Log log) { + DependencyVersionMap() { this.parentsVisitor = new ParentsVisitor(); } diff --git a/enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/RequireReleaseDeps.java b/enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/dependency/RequireReleaseDeps.java similarity index 62% rename from enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/RequireReleaseDeps.java rename to enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/dependency/RequireReleaseDeps.java index 3875a7d4..246ae7c9 100644 --- a/enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/RequireReleaseDeps.java +++ b/enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/dependency/RequireReleaseDeps.java @@ -16,17 +16,18 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.maven.plugins.enforcer; +package org.apache.maven.enforcer.rules.dependency; + +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.EnforcerRuleException; -import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; import org.apache.maven.enforcer.rules.utils.ArtifactUtils; -import org.apache.maven.project.MavenProject; -import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; +import org.apache.maven.execution.MavenSession; import static java.util.Optional.ofNullable; import static org.apache.maven.enforcer.rules.utils.ArtifactUtils.matchDependencyArtifact; @@ -36,48 +37,40 @@ * * @author Brian Fox */ -public class RequireReleaseDeps extends BannedDependenciesBase { +@Named("requireReleaseDeps") +public final class RequireReleaseDeps extends BannedDependenciesBase { /** * Allows this rule to execute only when this project is a release. - * - * @see {@link #setOnlyWhenRelease(boolean)} - * @see {@link #isOnlyWhenRelease()} - * */ private boolean onlyWhenRelease = false; /** * Allows this rule to fail when the parent is defined as a snapshot. - * - * @see {@link #setFailWhenParentIsSnapshot(boolean)} - * @see {@link #isFailWhenParentIsSnapshot()} */ private boolean failWhenParentIsSnapshot = true; + @Inject + public RequireReleaseDeps(MavenSession session, ResolveUtil resolveUtil) { + super(session, resolveUtil); + } + // Override parent to allow optional ignore of this rule. @Override - public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { + public void execute() throws EnforcerRuleException { boolean callSuper; - MavenProject project = null; if (onlyWhenRelease) { - // get the project - project = getProject(helper); - // only call super if this project is a release - callSuper = !project.getArtifact().isSnapshot(); + callSuper = !getSession().getCurrentProject().getArtifact().isSnapshot(); } else { callSuper = true; } if (callSuper) { - super.execute(helper); + super.execute(); if (failWhenParentIsSnapshot) { - if (project == null) { - project = getProject(helper); - } - Artifact parentArtifact = project.getParentArtifact(); + Artifact parentArtifact = getSession().getCurrentProject().getParentArtifact(); if (parentArtifact != null) { Set singletonArtifact = new HashSet<>(); @@ -100,60 +93,51 @@ protected String getErrorMessage() { return "is not a release dependency"; } - /** - * @param helper - * @return The evaluated {@link MavenProject}. - * @throws EnforcerRuleException - */ - private MavenProject getProject(EnforcerRuleHelper helper) throws EnforcerRuleException { - try { - return (MavenProject) helper.evaluate("${project}"); - } catch (ExpressionEvaluationException eee) { - throw new EnforcerRuleException("Unable to retrieve the MavenProject: ", eee); - } - } - @Override protected boolean validate(Artifact artifact) { // only check isSnapshot() if the artifact does not match (excludes minus includes) // otherwise true - return (matchDependencyArtifact(artifact, excludes) && !matchDependencyArtifact(artifact, includes)) + return (matchDependencyArtifact(artifact, getExcludes()) && !matchDependencyArtifact(artifact, getIncludes())) || !artifact.isSnapshot(); } - /* + /** * Filter the dependency artifacts according to the includes and excludes * If includes and excludes are both null, the original set is returned. * * @param dependencies the list of dependencies to filter * @return the resulting set of dependencies */ - protected Set filterArtifacts(Set dependencies) throws EnforcerRuleException { - if (includes != null) { - dependencies = ArtifactUtils.filterDependencyArtifacts(dependencies, includes); + private Set filterArtifacts(Set dependencies) throws EnforcerRuleException { + if (getIncludes() != null) { + dependencies = ArtifactUtils.filterDependencyArtifacts(dependencies, getIncludes()); } - if (dependencies != null && excludes != null) { - ofNullable(ArtifactUtils.filterDependencyArtifacts(dependencies, excludes)) + if (dependencies != null && getExcludes() != null) { + ofNullable(ArtifactUtils.filterDependencyArtifacts(dependencies, getExcludes())) .ifPresent(dependencies::removeAll); } return dependencies; } - public final boolean isOnlyWhenRelease() { - return onlyWhenRelease; - } - - public final void setOnlyWhenRelease(boolean onlyWhenRelease) { + public void setOnlyWhenRelease(boolean onlyWhenRelease) { this.onlyWhenRelease = onlyWhenRelease; } - public final boolean isFailWhenParentIsSnapshot() { - return failWhenParentIsSnapshot; + public void setFailWhenParentIsSnapshot(boolean failWhenParentIsSnapshot) { + this.failWhenParentIsSnapshot = failWhenParentIsSnapshot; } - public final void setFailWhenParentIsSnapshot(boolean failWhenParentIsSnapshot) { - this.failWhenParentIsSnapshot = failWhenParentIsSnapshot; + @Override + public String toString() { + return String.format( + "RequireReleaseDeps[message=%s, excludes=%s, includes=%s, searchTransitive=%b, onlyWhenRelease=%b, failWhenParentIsSnapshot=%b]", + getMessage(), + getExcludes(), + getIncludes(), + isSearchTransitive(), + onlyWhenRelease, + failWhenParentIsSnapshot); } } diff --git a/enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/RequireUpperBoundDeps.java b/enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/dependency/RequireUpperBoundDeps.java similarity index 94% rename from enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/RequireUpperBoundDeps.java rename to enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/dependency/RequireUpperBoundDeps.java index acbcec6d..c5c7a382 100644 --- a/enforcer-rules/src/main/java/org/apache/maven/plugins/enforcer/RequireUpperBoundDeps.java +++ b/enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/dependency/RequireUpperBoundDeps.java @@ -16,24 +16,27 @@ * specific language governing permissions and limitations * under the License. */ -package org.apache.maven.plugins.enforcer; +package org.apache.maven.enforcer.rules.dependency; + +import javax.inject.Inject; +import javax.inject.Named; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.versioning.ArtifactVersion; import org.apache.maven.artifact.versioning.DefaultArtifactVersion; import org.apache.maven.artifact.versioning.OverConstrainedVersionException; import org.apache.maven.enforcer.rule.api.EnforcerRuleException; -import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; +import org.apache.maven.enforcer.rules.AbstractStandardEnforcerRule; import org.apache.maven.enforcer.rules.utils.ArtifactUtils; import org.apache.maven.enforcer.rules.utils.ParentNodeProvider; import org.apache.maven.enforcer.rules.utils.ParentsVisitor; -import org.apache.maven.plugin.logging.Log; import org.apache.maven.shared.utils.logging.MessageUtils; import org.eclipse.aether.graph.DependencyNode; import org.eclipse.aether.graph.DependencyVisitor; @@ -45,8 +48,8 @@ * @author Geoffrey De Smet * @since 1.1 */ -public class RequireUpperBoundDeps extends AbstractNonCacheableEnforcerRule { - private static Log log; +@Named("requireUpperBoundDeps") +public final class RequireUpperBoundDeps extends AbstractStandardEnforcerRule { /** * @since 1.3 @@ -69,6 +72,13 @@ public class RequireUpperBoundDeps extends AbstractNonCacheableEnforcerRule { private RequireUpperBoundDepsVisitor upperBoundDepsVisitor; + private final ResolveUtil resolveUtil; + + @Inject + public RequireUpperBoundDeps(ResolveUtil resolveUtil) { + this.resolveUtil = Objects.requireNonNull(resolveUtil); + } + /** * Set to {@code true} if timestamped snapshots should be used. * @@ -97,11 +107,8 @@ public void setIncludes(List includes) { } @Override - public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { - if (log == null) { - log = helper.getLog(); - } - DependencyNode node = ArtifactUtils.resolveTransitiveDependencies(helper); + public void execute() throws EnforcerRuleException { + DependencyNode node = resolveUtil.resolveTransitiveDependencies(); upperBoundDepsVisitor = new RequireUpperBoundDepsVisitor() .setUniqueVersions(uniqueVersions) .setIncludes(includes); @@ -119,7 +126,7 @@ private List buildErrorMessages(List> conflicts) { org.eclipse.aether.artifact.Artifact artifact = conflict.get(0).getArtifact(); String groupArt = artifact.getGroupId() + ":" + artifact.getArtifactId(); if (excludes != null && excludes.contains(groupArt)) { - log.info("Ignoring requireUpperBoundDeps in " + groupArt); + getLog().info("Ignoring requireUpperBoundDeps in " + groupArt); } else { errorMessages.add(buildErrorMessage(conflict)); } diff --git a/enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/dependency/ResolveUtil.java b/enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/dependency/ResolveUtil.java new file mode 100644 index 00000000..8eb82780 --- /dev/null +++ b/enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/dependency/ResolveUtil.java @@ -0,0 +1,107 @@ +/* + * 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. + */ +package org.apache.maven.enforcer.rules.dependency; + +import javax.inject.Inject; +import javax.inject.Named; + +import java.util.Objects; +import java.util.stream.Collectors; + +import org.apache.maven.RepositoryUtils; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.enforcer.rule.api.EnforcerRuleException; +import org.apache.maven.execution.MavenSession; +import org.apache.maven.model.DependencyManagement; +import org.apache.maven.project.MavenProject; +import org.eclipse.aether.DefaultRepositorySystemSession; +import org.eclipse.aether.RepositorySystem; +import org.eclipse.aether.artifact.ArtifactTypeRegistry; +import org.eclipse.aether.collection.CollectRequest; +import org.eclipse.aether.collection.DependencyCollectionException; +import org.eclipse.aether.collection.DependencySelector; +import org.eclipse.aether.graph.DependencyNode; +import org.eclipse.aether.util.graph.manager.DependencyManagerUtils; +import org.eclipse.aether.util.graph.selector.AndDependencySelector; +import org.eclipse.aether.util.graph.transformer.ConflictResolver; + +import static java.util.Optional.ofNullable; + +/** + * Resolver helper class. + */ +@Named +class ResolveUtil { + + private final RepositorySystem repositorySystem; + private final MavenSession session; + + /** + * Default constructor + */ + @Inject + ResolveUtil(RepositorySystem repositorySystem, MavenSession session) { + this.repositorySystem = Objects.requireNonNull(repositorySystem); + this.session = Objects.requireNonNull(session); + } + + /** + * Retrieves the {@link DependencyNode} instance containing the result of the transitive dependency + * for the current {@link MavenProject}. + * + * @param selectors zero or more {@link DependencySelector} instances + * @return a Dependency Node which is the root of the project's dependency tree + * @throws EnforcerRuleException thrown if the lookup fails + */ + DependencyNode resolveTransitiveDependencies(DependencySelector... selectors) throws EnforcerRuleException { + try { + MavenProject project = session.getCurrentProject(); + ArtifactTypeRegistry artifactTypeRegistry = + session.getRepositorySession().getArtifactTypeRegistry(); + + DefaultRepositorySystemSession repositorySystemSession = + new DefaultRepositorySystemSession(session.getRepositorySession()); + repositorySystemSession.setConfigProperty(ConflictResolver.CONFIG_PROP_VERBOSE, true); + repositorySystemSession.setConfigProperty(DependencyManagerUtils.CONFIG_PROP_VERBOSE, true); + if (selectors.length > 0) { + repositorySystemSession.setDependencySelector(new AndDependencySelector(selectors)); + } + + CollectRequest collectRequest = new CollectRequest( + project.getDependencies().stream() + .map(d -> RepositoryUtils.toDependency(d, artifactTypeRegistry)) + .collect(Collectors.toList()), + ofNullable(project.getDependencyManagement()) + .map(DependencyManagement::getDependencies) + .map(list -> list.stream() + .map(d -> RepositoryUtils.toDependency(d, artifactTypeRegistry)) + .collect(Collectors.toList())) + .orElse(null), + project.getRemoteProjectRepositories()); + Artifact artifact = project.getArtifact(); + collectRequest.setRootArtifact(RepositoryUtils.toArtifact(artifact)); + + return repositorySystem + .collectDependencies(repositorySystemSession, collectRequest) + .getRoot(); + } catch (DependencyCollectionException e) { + throw new EnforcerRuleException("Could not build dependency tree " + e.getLocalizedMessage(), e); + } + } +} diff --git a/enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/utils/ArtifactMatcher.java b/enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/utils/ArtifactMatcher.java index 83fb00ce..0f2d774b 100644 --- a/enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/utils/ArtifactMatcher.java +++ b/enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/utils/ArtifactMatcher.java @@ -37,7 +37,6 @@ * This class is used for matching Artifacts against a list of patterns. * * @author Jakub Senko - * @see org.apache.maven.plugins.enforcer.BanTransitiveDependencies */ public final class ArtifactMatcher { diff --git a/enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/utils/ArtifactUtils.java b/enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/utils/ArtifactUtils.java index 68164d3b..4f8138c6 100644 --- a/enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/utils/ArtifactUtils.java +++ b/enforcer-rules/src/main/java/org/apache/maven/enforcer/rules/utils/ArtifactUtils.java @@ -19,7 +19,6 @@ package org.apache.maven.enforcer.rules.utils; import java.util.Collection; -import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; @@ -28,22 +27,7 @@ import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; import org.apache.maven.enforcer.rule.api.EnforcerRuleException; -import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.model.DependencyManagement; -import org.apache.maven.project.MavenProject; -import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; -import org.codehaus.plexus.component.repository.exception.ComponentLookupException; -import org.eclipse.aether.DefaultRepositorySystemSession; -import org.eclipse.aether.RepositorySystem; -import org.eclipse.aether.artifact.ArtifactTypeRegistry; -import org.eclipse.aether.collection.CollectRequest; -import org.eclipse.aether.collection.DependencyCollectionException; -import org.eclipse.aether.collection.DependencySelector; import org.eclipse.aether.graph.DependencyNode; -import org.eclipse.aether.util.graph.manager.DependencyManagerUtils; -import org.eclipse.aether.util.graph.selector.AndDependencySelector; -import org.eclipse.aether.util.graph.transformer.ConflictResolver; import static java.util.Optional.ofNullable; @@ -72,75 +56,6 @@ public static Artifact toArtifact(DependencyNode node) { return artifact; } - /** - * Retrieves the {@link DependencyNode} instance containing the result of the transitive dependency - * for the current {@link MavenProject}. - * - * @param helper (may not be null) an instance of the {@link EnforcerRuleHelper} class - * @param selectors zero or more {@link DependencySelector} instances - * @return a Dependency Node which is the root of the project's dependency tree - * @throws EnforcerRuleException thrown if the lookup fails - */ - public static DependencyNode resolveTransitiveDependencies( - EnforcerRuleHelper helper, DependencySelector... selectors) throws EnforcerRuleException { - try { - RepositorySystem repositorySystem = helper.getComponent(RepositorySystem.class); - MavenSession session = (MavenSession) helper.evaluate("${session}"); - MavenProject project = session.getCurrentProject(); - ArtifactTypeRegistry artifactTypeRegistry = - session.getRepositorySession().getArtifactTypeRegistry(); - - DefaultRepositorySystemSession repositorySystemSession = - new DefaultRepositorySystemSession(session.getRepositorySession()); - repositorySystemSession.setConfigProperty(ConflictResolver.CONFIG_PROP_VERBOSE, true); - repositorySystemSession.setConfigProperty(DependencyManagerUtils.CONFIG_PROP_VERBOSE, true); - if (selectors.length > 0) { - repositorySystemSession.setDependencySelector(new AndDependencySelector(selectors)); - } - - CollectRequest collectRequest = new CollectRequest( - project.getDependencies().stream() - .map(d -> RepositoryUtils.toDependency(d, artifactTypeRegistry)) - .collect(Collectors.toList()), - ofNullable(project.getDependencyManagement()) - .map(DependencyManagement::getDependencies) - .map(list -> list.stream() - .map(d -> RepositoryUtils.toDependency(d, artifactTypeRegistry)) - .collect(Collectors.toList())) - .orElse(null), - project.getRemoteProjectRepositories()); - Artifact artifact = project.getArtifact(); - collectRequest.setRootArtifact(RepositoryUtils.toArtifact(artifact)); - - return repositorySystem - .collectDependencies(repositorySystemSession, collectRequest) - .getRoot(); - } catch (ExpressionEvaluationException | ComponentLookupException e) { - throw new EnforcerRuleException("Unable to lookup a component " + e.getLocalizedMessage(), e); - } catch (DependencyCollectionException e) { - throw new EnforcerRuleException("Could not build dependency tree " + e.getLocalizedMessage(), e); - } - } - - /** - *

Retrieves all child dependency artifacts from the given {@link DependencyNode} and returns them - * as a set of {@link Artifact}.

- *

Note: Thus, the result will not contain the root artifact.

- * @param node root node - * @return set of all child dependency artifacts - */ - public static Set getDependencyArtifacts(DependencyNode node) { - return getDependencyArtifacts(node, new HashSet<>()); - } - - private static Set getDependencyArtifacts(DependencyNode node, Set set) { - node.getChildren().forEach(child -> { - set.add(toArtifact(child)); - getDependencyArtifacts(child, set); - }); - return set; - } - /** * Returns a subset of dependency artifacts that match the given collection of patterns * @@ -201,7 +116,7 @@ public static boolean matchDependencyArtifact(Artifact artifact, Collectiontrue if the artifact matches one of the patterns */ - static boolean compareDependency(String pattern, Artifact artifact) { + public static boolean compareDependency(String pattern, Artifact artifact) { return new ArtifactMatcher.Pattern(pattern).match(artifact); } } diff --git a/enforcer-rules/src/site/apt/banTransitiveDependencies.apt.vm b/enforcer-rules/src/site/apt/banTransitiveDependencies.apt.vm index 95265ca6..d388183f 100644 --- a/enforcer-rules/src/site/apt/banTransitiveDependencies.apt.vm +++ b/enforcer-rules/src/site/apt/banTransitiveDependencies.apt.vm @@ -29,17 +29,17 @@ Ban Transitive Dependencies The following parameters are supported by this rule: - * excludes - specify the dependencies that will be ignored.\ + * <> - specify the dependencies that will be ignored.\ This can be a list of artifacts in the format groupId[:artifactId[:version[:type[:scope[:classifier]]]]] . Wildcard '*' can be used to in place of specific section (e.g. group:*:1.0 will match both 'group:artifact:1.0' and 'group:anotherArtifact:1.0') Version is a string representing standard maven version range. Empty patterns will be ignored. - * includes - specify the dependencies that will be checked.\ + * <> - specify the dependencies that will be checked.\ These are exceptions to excludes intended for more convenient configuration. This can be a list of artifacts in the format groupId[:artifactId[:version[:type[:scope[:classifier]]]]] as above. - * message - an optional message to the user if the rule fails. Will replace generated report message. + * <> - an optional message to the user if the rule fails. Will replace generated report message. [] diff --git a/enforcer-rules/src/site/apt/bannedDependencies.apt.vm b/enforcer-rules/src/site/apt/bannedDependencies.apt.vm index c7325693..5018647f 100644 --- a/enforcer-rules/src/site/apt/bannedDependencies.apt.vm +++ b/enforcer-rules/src/site/apt/bannedDependencies.apt.vm @@ -30,9 +30,9 @@ Banned Dependencies The following parameters are supported by this rule: - * searchTransitive - if transitive dependencies should be checked. Default is true. + * <> - if transitive dependencies should be checked. Default is true. - * excludes - a list of artifacts to ban. The format is groupId[:artifactId][:version][:type][:scope][:classifier] where artifactId, version, type, scope and classifier are optional. Wildcards may be used to replace an entire or just parts of a section. + * <> - a list of artifacts to ban. The format is groupId[:artifactId][:version][:type][:scope][:classifier] where artifactId, version, type, scope and classifier are optional. Wildcards may be used to replace an entire or just parts of a section. Examples: * org.apache.maven @@ -53,11 +53,11 @@ Banned Dependencies [] - * includes - a list of artifacts to include. These are exceptions to the excludes. It is meant to allow wide exclusion rules with wildcards and fine tune using includes. If nothing has been excluded, then the includes have no effect. In otherwords, includes only subtract from artifacts that matched an exclude rule. + * <> - a list of artifacts to include. These are exceptions to the excludes. It is meant to allow wide exclusion rules with wildcards and fine tune using includes. If nothing has been excluded, then the includes have no effect. In otherwords, includes only subtract from artifacts that matched an exclude rule. For example, to ban all xerces except xerces-api you would exclude "xerces" (groupId) and include "xerces:xerces-api" - * message - an optional message to the user if the rule fails. + * <> - an optional message to the user if the rule fails. [] diff --git a/enforcer-rules/src/site/apt/dependencyConvergence.apt.vm b/enforcer-rules/src/site/apt/dependencyConvergence.apt.vm index 4f848f86..ca9d0446 100644 --- a/enforcer-rules/src/site/apt/dependencyConvergence.apt.vm +++ b/enforcer-rules/src/site/apt/dependencyConvergence.apt.vm @@ -133,10 +133,10 @@ and By default, all dependency convergence errors are reported, and any single error will fail the build. If you want to tune which dependency errors are reported and fail the build, you can add the following optional parameters: - * includes - A list of artifacts for which dependency convergence should be enforced. Not specifying any includes + * <> - A list of artifacts for which dependency convergence should be enforced. Not specifying any includes is interpreted the same as including all artifacts. - * excludes - A list of artifacts for which dependency convergence should not be enforced. These are exceptions + * <> - A list of artifacts for which dependency convergence should not be enforced. These are exceptions to the includes. [] diff --git a/enforcer-rules/src/site/apt/noSnapshots.apt.vm b/enforcer-rules/src/site/apt/noSnapshots.apt.vm deleted file mode 100644 index 8465b560..00000000 --- a/enforcer-rules/src/site/apt/noSnapshots.apt.vm +++ /dev/null @@ -1,72 +0,0 @@ -~~ 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. - - ------ - Require Release Dependencies - ------ - Brian Fox - ------ - November 2007 - ------ - -Require Release Dependencies - - This rule checks the dependencies and fails if any snapshots are found. - - - The following parameters are supported by this rule: - - * searchTransitive - if transitive dependencies should be checked. - - * message - an optional message to the user if the rule fails. - - [] - - - Sample Plugin Configuration: - -+---+ - - [...] - - - - org.apache.maven.plugins - maven-enforcer-plugin - ${project.version} - - - enforce-no-snapshots - - enforce - - - - - No Snapshots Allowed! - - - true - - - - - - - [...] - -+---+ \ No newline at end of file diff --git a/enforcer-rules/src/site/apt/requireReleaseDeps.apt.vm b/enforcer-rules/src/site/apt/requireReleaseDeps.apt.vm index 65566c2d..9311a005 100644 --- a/enforcer-rules/src/site/apt/requireReleaseDeps.apt.vm +++ b/enforcer-rules/src/site/apt/requireReleaseDeps.apt.vm @@ -30,17 +30,17 @@ Require Release Dependencies The following parameters are supported by this rule: - * searchTransitive - if transitive dependencies should be checked. Default: true + * <> - if transitive dependencies should be checked. Default: true - * message - an optional message to the user if the rule fails. + * <> - an optional message to the user if the rule fails. - * onlyWhenRelease - if this rule should only be executed when the version is a non-SNAPSHOT version. Default: false + * <> - if this rule should only be executed when the version is a non-SNAPSHOT version. Default: false - * failWhenParentIsSnapshot - if the parent should be checked. Default: true + * <> - if the parent should be checked. Default: true - * includes - List of dependency patterns to include when checking for snapshot versions. + * <> - List of dependency patterns to include when checking for snapshot versions. - * excludes - List of dependency patterns to exclude when checking for snapshot versions + * <> - List of dependency patterns to exclude when checking for snapshot versions [] diff --git a/enforcer-rules/src/test/java/org/apache/maven/enforcer/rules/dependency/BannedDependenciesTest.java b/enforcer-rules/src/test/java/org/apache/maven/enforcer/rules/dependency/BannedDependenciesTest.java new file mode 100644 index 00000000..69ad445d --- /dev/null +++ b/enforcer-rules/src/test/java/org/apache/maven/enforcer/rules/dependency/BannedDependenciesTest.java @@ -0,0 +1,182 @@ +/* + * 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. + */ +package org.apache.maven.enforcer.rules.dependency; + +import java.util.Collections; + +import org.apache.maven.enforcer.rule.api.EnforcerRuleException; +import org.apache.maven.enforcer.rules.utils.DependencyNodeBuilder; +import org.apache.maven.execution.MavenSession; +import org.apache.maven.plugin.testing.ArtifactStubFactory; +import org.apache.maven.project.MavenProject; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.mockito.Mockito.when; + +/** + * The Class BannedDependenciesTest. + * + * @author Brian Fox + */ +@ExtendWith(MockitoExtension.class) +class BannedDependenciesTest { + + private static final ArtifactStubFactory ARTIFACT_STUB_FACTORY = new ArtifactStubFactory(); + + @Mock + private MavenProject project; + + @Mock + private MavenSession session; + + @Mock + private ResolveUtil resolveUtil; + + @InjectMocks + private BannedDependencies rule; + + @Test + void excludesDoNotUseTransitiveDependencies() throws Exception { + when(session.getCurrentProject()).thenReturn(project); + when(project.getDependencyArtifacts()).thenReturn(ARTIFACT_STUB_FACTORY.getScopedArtifacts()); + + rule.setSearchTransitive(false); + rule.setExcludes(Collections.singletonList("*")); + + assertThatCode(rule::execute) + .isInstanceOf(EnforcerRuleException.class) + .hasMessageContaining("g:runtime:jar:1.0 <--- banned via the exclude/include list") + .hasMessageContaining("g:compile:jar:1.0 <--- banned via the exclude/include list") + .hasMessageContaining("g:provided:jar:1.0 <--- banned via the exclude/include list") + .hasMessageContaining("g:test:jar:1.0 <--- banned via the exclude/include list") + .hasMessageContaining("g:system:jar:1.0 <--- banned via the exclude/include list"); + } + + @Test + void excludesAndIncludesDoNotUseTransitiveDependencies() throws Exception { + when(session.getCurrentProject()).thenReturn(project); + when(project.getDependencyArtifacts()).thenReturn(ARTIFACT_STUB_FACTORY.getScopedArtifacts()); + + rule.setSearchTransitive(false); + rule.setExcludes(Collections.singletonList("*")); + rule.setIncludes(Collections.singletonList("g:compile")); + + assertThatCode(rule::execute) + .isInstanceOf(EnforcerRuleException.class) + .hasMessageContaining("g:runtime:jar:1.0 <--- banned via the exclude/include list") + .hasMessageContaining("g:provided:jar:1.0 <--- banned via the exclude/include list") + .hasMessageContaining("g:test:jar:1.0 <--- banned via the exclude/include list") + .hasMessageContaining("g:system:jar:1.0 <--- banned via the exclude/include list") + .hasMessageNotContaining("g:compile:jar:1.0"); + } + + @Test + void excludesUseTransitiveDependencies() throws Exception { + + when(resolveUtil.resolveTransitiveDependencies()) + .thenReturn(new DependencyNodeBuilder() + .withType(DependencyNodeBuilder.Type.POM) + .withChildNode(new DependencyNodeBuilder() + .withArtifactId("childA") + .withVersion("1.0.0") + .withChildNode(new DependencyNodeBuilder() + .withType(DependencyNodeBuilder.Type.WAR) + .withArtifactId("childAA") + .withVersion("1.0.0-SNAPSHOT") + .build()) + .withChildNode(new DependencyNodeBuilder() + .withType(DependencyNodeBuilder.Type.WAR) + .withArtifactId("childAB") + .withVersion("1.0.0-SNAPSHOT") + .build()) + .build()) + .build()); + + rule.setSearchTransitive(true); + rule.setExcludes(Collections.singletonList("*:*:*:war")); + + assertThatCode(rule::execute) + .isInstanceOf(EnforcerRuleException.class) + .hasMessageContaining( + "default-group:childAA:war:classifier:1.0.0-SNAPSHOT <--- banned via the exclude/include list") + .hasMessageContaining( + "default-group:childAB:war:classifier:1.0.0-SNAPSHOT <--- banned via the exclude/include list"); + } + + @Test + void excludesAndIncludesUseTransitiveDependencies() throws Exception { + + when(resolveUtil.resolveTransitiveDependencies()) + .thenReturn(new DependencyNodeBuilder() + .withType(DependencyNodeBuilder.Type.POM) + .withChildNode(new DependencyNodeBuilder() + .withArtifactId("childA") + .withVersion("1.0.0") + .withChildNode(new DependencyNodeBuilder() + .withType(DependencyNodeBuilder.Type.WAR) + .withArtifactId("childAA") + .withVersion("1.0.0-SNAPSHOT") + .build()) + .withChildNode(new DependencyNodeBuilder() + .withType(DependencyNodeBuilder.Type.WAR) + .withArtifactId("childAB") + .withVersion("1.0.0-SNAPSHOT") + .build()) + .build()) + .build()); + + rule.setSearchTransitive(true); + rule.setExcludes(Collections.singletonList("*:*:*:war")); + rule.setIncludes(Collections.singletonList("*:childAB:*:war")); + + assertThatCode(rule::execute) + .isInstanceOf(EnforcerRuleException.class) + .hasMessageContaining( + "default-group:childAA:war:classifier:1.0.0-SNAPSHOT <--- banned via the exclude/include list") + .hasMessageNotContaining("childAB"); + } + + @Test + void invalidExcludeFormat() throws Exception { + when(session.getCurrentProject()).thenReturn(project); + when(project.getDependencyArtifacts()).thenReturn(ARTIFACT_STUB_FACTORY.getScopedArtifacts()); + + rule.setSearchTransitive(false); + rule.setExcludes(Collections.singletonList("::::::::::")); + + assertThatCode(rule::execute).isInstanceOf(IllegalArgumentException.class); + } + + @Test + void invalidIncludeFormat() throws Exception { + when(session.getCurrentProject()).thenReturn(project); + when(project.getDependencyArtifacts()).thenReturn(ARTIFACT_STUB_FACTORY.getScopedArtifacts()); + + rule.setSearchTransitive(false); + rule.setExcludes(Collections.singletonList("*")); + rule.setIncludes(Collections.singletonList("*:*:x:x:x:x:x:x:x:x:")); + + assertThatCode(rule::execute).isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/enforcer-rules/src/test/java/org/apache/maven/enforcer/rules/dependency/RequireReleaseDepsTest.java b/enforcer-rules/src/test/java/org/apache/maven/enforcer/rules/dependency/RequireReleaseDepsTest.java new file mode 100644 index 00000000..0f5f1df1 --- /dev/null +++ b/enforcer-rules/src/test/java/org/apache/maven/enforcer/rules/dependency/RequireReleaseDepsTest.java @@ -0,0 +1,184 @@ +/* + * 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. + */ +package org.apache.maven.enforcer.rules.dependency; + +import java.io.IOException; +import java.util.Collections; + +import org.apache.maven.enforcer.rule.api.EnforcerRuleException; +import org.apache.maven.enforcer.rules.utils.DependencyNodeBuilder; +import org.apache.maven.execution.MavenSession; +import org.apache.maven.plugin.testing.ArtifactStubFactory; +import org.apache.maven.project.MavenProject; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.apache.maven.plugins.enforcer.EnforcerTestUtils.getDependencyNodeWithMultipleSnapshots; +import static org.apache.maven.plugins.enforcer.EnforcerTestUtils.getDependencyNodeWithMultipleTestSnapshots; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +/** + * Unit tests for {@link RequireReleaseDeps} + * + * @author Brian Fox, Andrzej Jarmoniuk + */ +@ExtendWith(MockitoExtension.class) +class RequireReleaseDepsTest { + private static final ArtifactStubFactory ARTIFACT_STUB_FACTORY = new ArtifactStubFactory(); + + @Mock + private MavenProject project; + + @Mock + private MavenSession session; + + @Mock + private ResolveUtil resolveUtil; + + @InjectMocks + private RequireReleaseDeps rule; + + @BeforeEach + void setUp() { + // ruleHelper = EnforcerTestUtils.getHelper(project); + // rule = new RequireReleaseDeps(); + } + + @Test + void testSearchNonTransitive() throws IOException { + when(session.getCurrentProject()).thenReturn(project); + when(project.getDependencyArtifacts()).thenReturn(ARTIFACT_STUB_FACTORY.getScopedArtifacts()); + rule.setSearchTransitive(false); + + assertThatCode(rule::execute).doesNotThrowAnyException(); + + verifyNoInteractions(resolveUtil); + } + + @Test + void testSearchTransitiveMultipleFailures() throws Exception { + when(resolveUtil.resolveTransitiveDependencies()).thenReturn(getDependencyNodeWithMultipleSnapshots()); + rule.setSearchTransitive(true); + + assertThatCode(rule::execute) + .isInstanceOf(EnforcerRuleException.class) + .hasMessageContaining( + "default-group:childAA:jar:classifier:1.0.0-SNAPSHOT <--- is not a release dependency") + .hasMessageContaining( + "default-group:childB:jar:classifier:2.0.0-SNAPSHOT <--- is not a release dependency"); + } + + @Test + void testSearchTransitiveNoFailures() throws Exception { + when(session.getCurrentProject()).thenReturn(project); + when(resolveUtil.resolveTransitiveDependencies()).thenReturn(new DependencyNodeBuilder().build()); + + rule.setSearchTransitive(true); + assertThatCode(rule::execute).doesNotThrowAnyException(); + } + + @Test + void testShouldFailOnlyWhenRelease() throws Exception { + when(session.getCurrentProject()).thenReturn(project); + when(project.getArtifact()).thenReturn(ARTIFACT_STUB_FACTORY.getSnapshotArtifact()); + rule.setOnlyWhenRelease(true); + + assertThatCode(rule::execute).doesNotThrowAnyException(); + + verifyNoInteractions(resolveUtil); + } + + @Test + void testWildcardExcludeTests() throws Exception { + when(session.getCurrentProject()).thenReturn(project); + when(resolveUtil.resolveTransitiveDependencies()).thenReturn(getDependencyNodeWithMultipleTestSnapshots()); + + rule.setExcludes(Collections.singletonList("*:*:*:*:test")); + rule.setSearchTransitive(true); + + assertThatCode(rule::execute).doesNotThrowAnyException(); + } + + @Test + void testWildcardExcludeAll() throws Exception { + when(session.getCurrentProject()).thenReturn(project); + when(resolveUtil.resolveTransitiveDependencies()).thenReturn(getDependencyNodeWithMultipleTestSnapshots()); + + rule.setExcludes(Collections.singletonList("*")); + rule.setSearchTransitive(true); + + assertThatCode(rule::execute).doesNotThrowAnyException(); + } + + @Test + void testExcludesAndIncludes() throws Exception { + when(resolveUtil.resolveTransitiveDependencies()).thenReturn(getDependencyNodeWithMultipleTestSnapshots()); + + rule.setExcludes(Collections.singletonList("*")); + rule.setIncludes(Collections.singletonList("*:*:*:*:test")); + rule.setSearchTransitive(true); + + assertThatCode(rule::execute) + .isInstanceOf(EnforcerRuleException.class) + .hasMessageContaining( + "default-group:childAA:jar:classifier:1.0.0-SNAPSHOT <--- is not a release dependency") + .hasMessageContaining( + "default-group:childB:jar:classifier:2.0.0-SNAPSHOT <--- is not a release dependency"); + } + + /** + * Test id. + */ + @Test + void testId() { + assertThat(rule.getCacheId()).isNull(); + } + + @Test + void testFailWhenParentIsSnapshot() throws Exception { + when(session.getCurrentProject()).thenReturn(project); + when(project.getParentArtifact()).thenReturn(ARTIFACT_STUB_FACTORY.getSnapshotArtifact()); + when(resolveUtil.resolveTransitiveDependencies()).thenReturn(new DependencyNodeBuilder().build()); + + rule.setFailWhenParentIsSnapshot(true); + + assertThatCode(rule::execute) + .isInstanceOf(EnforcerRuleException.class) + .hasMessageContaining("Parent Cannot be a snapshot: testGroupId:snapshot:jar:2.0-SNAPSHOT"); + } + + @Test + void parentShouldBeExcluded() throws Exception { + when(session.getCurrentProject()).thenReturn(project); + when(project.getParentArtifact()).thenReturn(ARTIFACT_STUB_FACTORY.getSnapshotArtifact()); + when(resolveUtil.resolveTransitiveDependencies()).thenReturn(new DependencyNodeBuilder().build()); + + rule.setFailWhenParentIsSnapshot(true); + rule.setExcludes(Collections.singletonList("testGroupId:*")); + + assertThatCode(rule::execute).doesNotThrowAnyException(); + } +} diff --git a/enforcer-rules/src/test/java/org/apache/maven/enforcer/rules/dependency/RequireUpperBoundDepsTest.java b/enforcer-rules/src/test/java/org/apache/maven/enforcer/rules/dependency/RequireUpperBoundDepsTest.java new file mode 100644 index 00000000..5cbbe30e --- /dev/null +++ b/enforcer-rules/src/test/java/org/apache/maven/enforcer/rules/dependency/RequireUpperBoundDepsTest.java @@ -0,0 +1,62 @@ +/* + * 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. + */ +package org.apache.maven.enforcer.rules.dependency; + +import org.apache.maven.enforcer.rule.api.EnforcerRuleException; +import org.apache.maven.enforcer.rules.utils.DependencyNodeBuilder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class RequireUpperBoundDepsTest { + + @Mock + private ResolveUtil resolveUtil; + + @InjectMocks + private RequireUpperBoundDeps rule; + + @Test + void testRule() throws Exception { + + when(resolveUtil.resolveTransitiveDependencies()) + .thenReturn(new DependencyNodeBuilder() + .withType(DependencyNodeBuilder.Type.POM) + .withChildNode(new DependencyNodeBuilder() + .withArtifactId("childA") + .withVersion("1.0.0") + .build()) + .withChildNode(new DependencyNodeBuilder() + .withArtifactId("childA") + .withVersion("2.0.0") + .build()) + .build()); + + assertThatCode(rule::execute) + .isInstanceOf(EnforcerRuleException.class) + .hasMessageContaining("default-group:childA:1.0.0:classifier") + .hasMessageContaining("default-group:childA:2.0.0:classifier"); + } +} diff --git a/enforcer-rules/src/test/java/org/apache/maven/plugins/enforcer/BannedDependenciesTestSetup.java b/enforcer-rules/src/test/java/org/apache/maven/plugins/enforcer/BannedDependenciesTestSetup.java deleted file mode 100644 index 7f3e9762..00000000 --- a/enforcer-rules/src/test/java/org/apache/maven/plugins/enforcer/BannedDependenciesTestSetup.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * 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. - */ -package org.apache.maven.plugins.enforcer; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.maven.enforcer.rule.api.EnforcerRuleException; -import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; -import org.apache.maven.plugin.testing.ArtifactStubFactory; -import org.apache.maven.project.MavenProject; - -public class BannedDependenciesTestSetup { - private final MavenProject project; - - public BannedDependenciesTestSetup() throws IOException { - this.excludes = new ArrayList<>(); - this.includes = new ArrayList<>(); - - ArtifactStubFactory factory = new ArtifactStubFactory(); - - project = new MockProject(); - project.setDependencyArtifacts(factory.getScopedArtifacts()); - - this.helper = EnforcerTestUtils.getHelper(project); - - this.rule = new BannedDependencies(); - this.rule.setMessage(null); - - this.rule.setExcludes(this.excludes); - this.rule.setIncludes(this.includes); - } - - private List excludes; - - private final List includes; - - private final BannedDependencies rule; - - private final EnforcerRuleHelper helper; - - public void setSearchTransitive(boolean searchTransitive) { - rule.setSearchTransitive(searchTransitive); - } - - public void addExcludeAndRunRule(String toAdd) throws EnforcerRuleException { - excludes.add(toAdd); - rule.execute(helper); - } - - public void addIncludeExcludeAndRunRule(String incAdd, String excAdd) throws EnforcerRuleException { - excludes.add(excAdd); - includes.add(incAdd); - rule.execute(helper); - } - - public List getExcludes() { - return excludes; - } - - public void setExcludes(List excludes) { - this.excludes = excludes; - } -} diff --git a/enforcer-rules/src/test/java/org/apache/maven/plugins/enforcer/RequireUpperBoundDepsTest.java b/enforcer-rules/src/test/java/org/apache/maven/plugins/enforcer/RequireUpperBoundDepsTest.java deleted file mode 100644 index 59be79b9..00000000 --- a/enforcer-rules/src/test/java/org/apache/maven/plugins/enforcer/RequireUpperBoundDepsTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * 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. - */ -package org.apache.maven.plugins.enforcer; - -import org.apache.maven.enforcer.rule.api.EnforcerRuleException; -import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; -import org.apache.maven.enforcer.rules.utils.DependencyNodeBuilder; -import org.junit.jupiter.api.Test; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.junit.jupiter.api.Assertions.fail; - -public class RequireUpperBoundDepsTest { - - @Test - public void testRule() { - MockProject project = new MockProject(); - EnforcerRuleHelper helper = EnforcerTestUtils.getHelper(project); - RequireUpperBoundDeps rule = new RequireUpperBoundDeps(); - EnforcerTestUtils.provideCollectDependencies(new DependencyNodeBuilder() - .withType(DependencyNodeBuilder.Type.POM) - .withChildNode(new DependencyNodeBuilder() - .withArtifactId("childA") - .withVersion("1.0.0") - .build()) - .withChildNode(new DependencyNodeBuilder() - .withArtifactId("childA") - .withVersion("2.0.0") - .build()) - .build()); - - try { - rule.execute(helper); - fail("Did not detect upper bounds error"); - } catch (EnforcerRuleException ex) { - assertThat(ex.getMessage(), containsString("default-group:childA:1.0.0:classifier")); - assertThat(ex.getMessage(), containsString("default-group:childA:2.0.0:classifier")); - } - } -} diff --git a/enforcer-rules/src/test/java/org/apache/maven/plugins/enforcer/TestBannedDependencies.java b/enforcer-rules/src/test/java/org/apache/maven/plugins/enforcer/TestBannedDependencies.java deleted file mode 100644 index 069fb32d..00000000 --- a/enforcer-rules/src/test/java/org/apache/maven/plugins/enforcer/TestBannedDependencies.java +++ /dev/null @@ -1,252 +0,0 @@ -/* - * 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. - */ -package org.apache.maven.plugins.enforcer; - -import java.io.IOException; - -import org.apache.maven.enforcer.rule.api.EnforcerRuleException; -import org.apache.maven.enforcer.rules.utils.DependencyNodeBuilder; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import static org.apache.maven.plugins.enforcer.EnforcerTestUtils.provideCollectDependencies; -import static org.junit.jupiter.api.Assertions.assertThrows; - -/** - * The Class TestBannedDependencies. - * - * @author Brian Fox - */ -public class TestBannedDependencies { - - public static class ExcludesDoNotUseTransitiveDependencies { - private BannedDependenciesTestSetup setup; - - @BeforeEach - public void beforeMethod() throws IOException { - this.setup = new BannedDependenciesTestSetup(); - this.setup.setSearchTransitive(false); - } - - private void addExcludeAndRunRule(String toAdd) throws EnforcerRuleException { - this.setup.addExcludeAndRunRule(toAdd); - } - - @Test - public void testGroupIdArtifactIdVersion() throws Exception { - addExcludeAndRunRule("testGroupId:release:1.0"); - } - - @Test - public void testGroupIdArtifactId() throws Exception { - addExcludeAndRunRule("testGroupId:release"); - } - - @Test - public void testGroupId() throws Exception { - addExcludeAndRunRule("testGroupId"); - } - } - - public static class ExcludesUsingTransitiveDependencies { - - private BannedDependenciesTestSetup setup; - - @BeforeEach - public void beforeMethod() throws IOException { - this.setup = new BannedDependenciesTestSetup(); - this.setup.setSearchTransitive(true); - } - - private void addExcludeAndRunRule(String toAdd) throws EnforcerRuleException { - this.setup.addExcludeAndRunRule(toAdd); - } - - @Test - public void testGroupIdArtifactIdVersion() { - assertThrows(EnforcerRuleException.class, () -> addExcludeAndRunRule("default-group:childA:1.0.0")); - } - - @Test - public void testGroupIdArtifactId() { - assertThrows(EnforcerRuleException.class, () -> addExcludeAndRunRule("default-group:childA")); - } - - @Test - public void testGroupId() { - assertThrows(EnforcerRuleException.class, () -> addExcludeAndRunRule("default-group")); - } - - @Test - public void testSpaceTrimmingGroupIdArtifactIdVersion() { - assertThrows( - EnforcerRuleException.class, - () -> addExcludeAndRunRule(" default-group : childA : 1.0.0 ")); - } - - @Test - public void groupIdArtifactIdVersionType() { - provideCollectDependencies(new DependencyNodeBuilder() - .withType(DependencyNodeBuilder.Type.POM) - .withChildNode(new DependencyNodeBuilder() - .withArtifactId("childA") - .withVersion("1.0.0") - .withChildNode(new DependencyNodeBuilder() - .withType(DependencyNodeBuilder.Type.WAR) - .withArtifactId("childAA") - .withVersion("1.0.0-SNAPSHOT") - .build()) - .build()) - .build()); - assertThrows(EnforcerRuleException.class, () -> addExcludeAndRunRule("*:*:*:war")); - } - - @Test - public void groupIdArtifactIdVersionTypeScope() { - EnforcerTestUtils.provideCollectDependencies( - EnforcerTestUtils.getDependencyNodeWithMultipleTestSnapshots()); - assertThrows(EnforcerRuleException.class, () -> addExcludeAndRunRule("*:*:*:*:test")); - } - - // @Test(expected = EnforcerRuleException.class) - // public void groupIdArtifactIdVersionTypeScopeClassifier() throws Exception { - // addExcludeAndRunRule("g:compile:1.0:jar:compile:one"); - // } - // - } - - public static class WildcardExcludesUsingTransitiveDependencies { - - private BannedDependenciesTestSetup setup; - - @BeforeEach - public void beforeMethod() throws IOException { - this.setup = new BannedDependenciesTestSetup(); - this.setup.setSearchTransitive(true); - } - - private void addExcludeAndRunRule(String toAdd) throws EnforcerRuleException { - this.setup.addExcludeAndRunRule(toAdd); - } - - @Test - public void testWildcardForGroupIdArtifactIdVersion() throws Exception { - assertThrows(EnforcerRuleException.class, () -> addExcludeAndRunRule("*:childA:1.0.0")); - } - - @Test - public void testWildCardForGroupIdArtifactId() { - assertThrows(EnforcerRuleException.class, () -> addExcludeAndRunRule("*:childA")); - } - - @Test - public void testWildcardForGroupIdWildcardForArtifactIdVersion() { - assertThrows(EnforcerRuleException.class, () -> addExcludeAndRunRule("*:*:1.0.0")); - } - - @Test - public void testWildcardForGroupIdArtifactIdWildcardForVersion() { - assertThrows(EnforcerRuleException.class, () -> addExcludeAndRunRule("*:childA:*")); - } - } - - public static class PartialWildcardExcludesUsingTransitiveDependencies { - - private BannedDependenciesTestSetup setup; - - @BeforeEach - public void beforeMethod() throws IOException { - this.setup = new BannedDependenciesTestSetup(); - this.setup.setSearchTransitive(true); - } - - private void addExcludeAndRunRule(String toAdd) throws EnforcerRuleException { - this.setup.addExcludeAndRunRule(toAdd); - } - - @Test - public void groupIdArtifactIdWithWildcard() { - assertThrows(EnforcerRuleException.class, () -> addExcludeAndRunRule("default-group:ch*")); - } - - @Test - public void groupIdArtifactIdVersionTypeWildcardScope() { - assertThrows(EnforcerRuleException.class, () -> addExcludeAndRunRule("default-group:childA:1.0.0:jar:co*")); - } - - @Test - public void groupIdArtifactIdVersionWildcardTypeScope() { - assertThrows( - EnforcerRuleException.class, () -> addExcludeAndRunRule("default-group:childA:1.0.0:j*:compile")); - } - } - - public static class IllegalFormatsTests { - private BannedDependenciesTestSetup setup; - - @BeforeEach - public void beforeMethod() throws IOException { - this.setup = new BannedDependenciesTestSetup(); - this.setup.setSearchTransitive(true); - } - - private void addExcludeAndRunRule(String toAdd) throws EnforcerRuleException { - this.setup.addExcludeAndRunRule(toAdd); - } - - @Test - public void onlyThreeColonsWithoutAnythingElse() { - assertThrows(IllegalArgumentException.class, () -> addExcludeAndRunRule(":::")); - } - - @Test - public void onlySevenColonsWithoutAnythingElse() { - assertThrows(IllegalArgumentException.class, () -> addExcludeAndRunRule(":::::::")); - } - } - - public static class IncludesExcludesNoTransitive { - private BannedDependenciesTestSetup setup; - - @BeforeEach - public void beforeMethod() throws IOException { - this.setup = new BannedDependenciesTestSetup(); - this.setup.setSearchTransitive(false); - } - - private void addIncludeExcludeAndRunRule(String incAdd, String excAdd) throws EnforcerRuleException { - this.setup.addIncludeExcludeAndRunRule(incAdd, excAdd); - } - - @Test - public void includeEverythingAndExcludeEverythign() throws EnforcerRuleException { - addIncludeExcludeAndRunRule("*", "*"); - } - - @Test - public void includeEverythingAndExcludeEveryGroupIdAndScopeRuntime() throws EnforcerRuleException { - addIncludeExcludeAndRunRule("*", "*:runtime"); - } - - @Test - public void includeEverythingAndExcludeEveryGroupIdAndScopeRuntimeYYYY() { - assertThrows(EnforcerRuleException.class, () -> addIncludeExcludeAndRunRule("*:test", "*:runtime")); - } - } -} diff --git a/enforcer-rules/src/test/java/org/apache/maven/plugins/enforcer/TestRequireReleaseDeps.java b/enforcer-rules/src/test/java/org/apache/maven/plugins/enforcer/TestRequireReleaseDeps.java deleted file mode 100644 index 41569e17..00000000 --- a/enforcer-rules/src/test/java/org/apache/maven/plugins/enforcer/TestRequireReleaseDeps.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * 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. - */ -package org.apache.maven.plugins.enforcer; - -import java.io.IOException; -import java.util.Collections; - -import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper; -import org.apache.maven.enforcer.rules.utils.EnforcerRuleUtilsHelper; -import org.apache.maven.plugin.testing.ArtifactStubFactory; -import org.apache.maven.project.MavenProject; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import static org.apache.maven.plugins.enforcer.EnforcerTestUtils.getDependencyNodeWithMultipleSnapshots; -import static org.apache.maven.plugins.enforcer.EnforcerTestUtils.getDependencyNodeWithMultipleTestSnapshots; -import static org.apache.maven.plugins.enforcer.EnforcerTestUtils.provideCollectDependencies; -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Unit tests for {@link RequireReleaseDeps} - * - * @author Brian Fox, Andrzej Jarmoniuk - */ -public class TestRequireReleaseDeps { - private MavenProject project; - private static final ArtifactStubFactory ARTIFACT_STUB_FACTORY = new ArtifactStubFactory(); - ; - private EnforcerRuleHelper ruleHelper; - private RequireReleaseDeps rule; - - @BeforeEach - public void setUp() { - project = new MockProject(); - ruleHelper = EnforcerTestUtils.getHelper(project); - rule = new RequireReleaseDeps(); - } - - @Test - public void testSearchNonTransitive() throws IOException { - project.setDependencyArtifacts(ARTIFACT_STUB_FACTORY.getScopedArtifacts()); - rule.setSearchTransitive(false); - EnforcerRuleUtilsHelper.execute(rule, ruleHelper, false); - } - - @Test - public void testSearchTransitiveMultipleFailures() { - rule.setSearchTransitive(true); - provideCollectDependencies(getDependencyNodeWithMultipleSnapshots()); - EnforcerRuleUtilsHelper.execute(rule, ruleHelper, true); - } - - @Test - public void testSearchTransitiveNoFailures() { - rule.setSearchTransitive(true); - EnforcerRuleUtilsHelper.execute(rule, ruleHelper, false); - } - - @Test - public void testShouldFailOnlyWhenRelease() throws IOException { - project.setArtifact(ARTIFACT_STUB_FACTORY.getSnapshotArtifact()); - provideCollectDependencies(getDependencyNodeWithMultipleSnapshots()); - rule.setOnlyWhenRelease(true); - EnforcerRuleUtilsHelper.execute(rule, ruleHelper, false); - } - - @Test - void testWildcardExcludeTests() throws Exception { - rule.setExcludes(Collections.singletonList("*:*:*:*:test")); - provideCollectDependencies(getDependencyNodeWithMultipleTestSnapshots()); - rule.setSearchTransitive(true); - EnforcerRuleUtilsHelper.execute(rule, ruleHelper, false); - } - - @Test - void testWildcardExcludeAll() throws Exception { - rule.setExcludes(Collections.singletonList("*")); - provideCollectDependencies(getDependencyNodeWithMultipleSnapshots()); - rule.setSearchTransitive(true); - EnforcerRuleUtilsHelper.execute(rule, ruleHelper, false); - } - - @Test - void testExcludesAndIncludes() throws Exception { - rule.setExcludes(Collections.singletonList("*")); - rule.setIncludes(Collections.singletonList("*:*:*:*:test")); - provideCollectDependencies(getDependencyNodeWithMultipleTestSnapshots()); - rule.setSearchTransitive(true); - EnforcerRuleUtilsHelper.execute(rule, ruleHelper, true); - } - - /** - * Test id. - */ - @Test - void testId() { - assertThat(rule.getCacheId()).isEqualTo("0"); - } - - @Test - void testFailWhenParentIsSnapshotFalse() throws IOException { - MavenProject parent = new MockProject(); - parent.setArtifact(ARTIFACT_STUB_FACTORY.getSnapshotArtifact()); - project.setParent(parent); - rule.setFailWhenParentIsSnapshot(false); - EnforcerRuleUtilsHelper.execute(rule, ruleHelper, false); - } - - @Test - void parentShouldBeExcluded() throws IOException { - MavenProject parent = new MockProject(); - parent.setArtifact(ARTIFACT_STUB_FACTORY.getSnapshotArtifact()); - project.setParent(parent); - rule.setExcludes(Collections.singletonList(parent.getArtifact().getGroupId() + ":*")); - EnforcerRuleUtilsHelper.execute(rule, ruleHelper, false); - } -} diff --git a/maven-enforcer-plugin/src/it/projects/MENFORCER-434/verify.groovy b/maven-enforcer-plugin/src/it/projects/MENFORCER-434/verify.groovy index 6ea93b46..6b1c801e 100644 --- a/maven-enforcer-plugin/src/it/projects/MENFORCER-434/verify.groovy +++ b/maven-enforcer-plugin/src/it/projects/MENFORCER-434/verify.groovy @@ -18,7 +18,7 @@ */ def buildLog = new File(basedir, 'build.log').text -assert buildLog.contains('[ERROR] Rule 0: org.apache.maven.plugins.enforcer.BannedDependencies failed with message:') +assert buildLog.contains('[ERROR] Rule 0: org.apache.maven.enforcer.rules.dependency.BannedDependencies failed with message:') assert buildLog.contains(' org.apache.logging.log4j:log4j-core:jar:2.19.0') assert buildLog.contains(' org.apache.logging.log4j:log4j-api:jar:2.19.0 <--- banned via the exclude/include list') diff --git a/maven-enforcer-plugin/src/it/projects/ban-transitive-dependencies-fail/verify.groovy b/maven-enforcer-plugin/src/it/projects/ban-transitive-dependencies-fail/verify.groovy index e8381cdc..93df359f 100644 --- a/maven-enforcer-plugin/src/it/projects/ban-transitive-dependencies-fail/verify.groovy +++ b/maven-enforcer-plugin/src/it/projects/ban-transitive-dependencies-fail/verify.groovy @@ -17,5 +17,5 @@ * under the License. */ File buildLog = new File( basedir, 'build.log' ) -assert buildLog.text.contains( '[ERROR] Rule 0: org.apache.maven.plugins.enforcer.BanTransitiveDependencies failed with message:' ) +assert buildLog.text.contains( '[ERROR] Rule 0: org.apache.maven.enforcer.rules.dependency.BanTransitiveDependencies failed with message:' ) \ No newline at end of file diff --git a/maven-enforcer-plugin/src/it/projects/banned-dependencies-versionrange-fail/verify.groovy b/maven-enforcer-plugin/src/it/projects/banned-dependencies-versionrange-fail/verify.groovy index 8a0f2952..73d370e4 100644 --- a/maven-enforcer-plugin/src/it/projects/banned-dependencies-versionrange-fail/verify.groovy +++ b/maven-enforcer-plugin/src/it/projects/banned-dependencies-versionrange-fail/verify.groovy @@ -17,5 +17,5 @@ * under the License. */ File buildLog = new File( basedir, 'build.log' ) -assert buildLog.text.contains( '[ERROR] Rule 0: org.apache.maven.plugins.enforcer.BannedDependencies failed with message:' ) +assert buildLog.text.contains( '[ERROR] Rule 0: org.apache.maven.enforcer.rules.dependency.BannedDependencies failed with message:' ) \ No newline at end of file diff --git a/maven-enforcer-plugin/src/it/projects/dependency-convergence_transitive_provided/verify.groovy b/maven-enforcer-plugin/src/it/projects/dependency-convergence_transitive_provided/verify.groovy index b89327f1..23c21909 100644 --- a/maven-enforcer-plugin/src/it/projects/dependency-convergence_transitive_provided/verify.groovy +++ b/maven-enforcer-plugin/src/it/projects/dependency-convergence_transitive_provided/verify.groovy @@ -20,7 +20,7 @@ File buildLog = new File(basedir, 'build.log') rulesExecuted = buildLog.readLines() - .findAll {it == '[INFO] Rule 0: org.apache.maven.plugins.enforcer.DependencyConvergence executed'} + .findAll {it == '[INFO] Rule 0: org.apache.maven.enforcer.rules.dependency.DependencyConvergence executed'} // Rule should be executed in each module assert rulesExecuted.size() == 3 \ No newline at end of file diff --git a/maven-enforcer-plugin/src/it/projects/multimodule-ban-transitive-dependencies_failure/verify.groovy b/maven-enforcer-plugin/src/it/projects/multimodule-ban-transitive-dependencies_failure/verify.groovy index c6657d7a..7415721c 100644 --- a/maven-enforcer-plugin/src/it/projects/multimodule-ban-transitive-dependencies_failure/verify.groovy +++ b/maven-enforcer-plugin/src/it/projects/multimodule-ban-transitive-dependencies_failure/verify.groovy @@ -18,5 +18,5 @@ */ File buildLog = new File( basedir, 'build.log' ) -assert buildLog.text.contains( 'Rule 0: org.apache.maven.plugins.enforcer.BanTransitiveDependencies failed with message:' ) +assert buildLog.text.contains( 'Rule 0: org.apache.maven.enforcer.rules.dependency.BanTransitiveDependencies failed with message:' ) assert buildLog.text.contains( 'org.apache.maven.its.enforcer:module1:jar:1.0-SNAPSHOT has transitive dependencies:' ) diff --git a/maven-enforcer-plugin/src/it/projects/multimodule-require-release-dependencies-exclude_failure/verify.groovy b/maven-enforcer-plugin/src/it/projects/multimodule-require-release-dependencies-exclude_failure/verify.groovy index f091ed1d..322a8def 100644 --- a/maven-enforcer-plugin/src/it/projects/multimodule-require-release-dependencies-exclude_failure/verify.groovy +++ b/maven-enforcer-plugin/src/it/projects/multimodule-require-release-dependencies-exclude_failure/verify.groovy @@ -18,5 +18,5 @@ */ File buildLog = new File( basedir, 'build.log' ) -assert buildLog.text.contains( 'Rule 0: org.apache.maven.plugins.enforcer.RequireReleaseDeps failed with message:' ) +assert buildLog.text.contains( 'Rule 0: org.apache.maven.enforcer.rules.dependency.RequireReleaseDeps failed with message:' ) assert buildLog.text =~ /org.apache.maven.its.enforcer:module1:jar:1.0-SNAPSHOT.*is not a release dependency/ \ No newline at end of file diff --git a/maven-enforcer-plugin/src/it/projects/multimodule-require-release-dependencies-snapshot-parent_failure/verify.groovy b/maven-enforcer-plugin/src/it/projects/multimodule-require-release-dependencies-snapshot-parent_failure/verify.groovy index eb308923..39b77205 100644 --- a/maven-enforcer-plugin/src/it/projects/multimodule-require-release-dependencies-snapshot-parent_failure/verify.groovy +++ b/maven-enforcer-plugin/src/it/projects/multimodule-require-release-dependencies-snapshot-parent_failure/verify.groovy @@ -18,5 +18,5 @@ */ File buildLog = new File( basedir, 'build.log' ) -assert buildLog.text.contains( 'Rule 0: org.apache.maven.plugins.enforcer.RequireReleaseDeps failed with message:' ) +assert buildLog.text.contains( 'Rule 0: org.apache.maven.enforcer.rules.dependency.RequireReleaseDeps failed with message:' ) assert buildLog.text.contains( 'Parent Cannot be a snapshot: org.apache.maven.its.enforcer:multimodule:pom:1.0-SNAPSHOT' ) diff --git a/maven-enforcer-plugin/src/it/projects/non-exeisting-optional-dependency/verify.groovy b/maven-enforcer-plugin/src/it/projects/non-exeisting-optional-dependency/verify.groovy index 3916cf3f..4529a4a6 100644 --- a/maven-enforcer-plugin/src/it/projects/non-exeisting-optional-dependency/verify.groovy +++ b/maven-enforcer-plugin/src/it/projects/non-exeisting-optional-dependency/verify.groovy @@ -23,8 +23,8 @@ assert buildLog.contains( '[WARNING] The POM for org.example:test-not-existing:j // rule executed assert buildLog.contains( '[INFO] Rule 0: org.apache.maven.enforcer.rules.AlwaysPass executed' ) -assert buildLog.contains( '[INFO] Rule 1: org.apache.maven.plugins.enforcer.BanTransitiveDependencies executed' ) -assert buildLog.contains( '[INFO] Rule 2: org.apache.maven.plugins.enforcer.BannedDependencies executed' ) -assert buildLog.contains( '[INFO] Rule 3: org.apache.maven.plugins.enforcer.DependencyConvergence executed') -assert buildLog.contains( '[INFO] Rule 4: org.apache.maven.plugins.enforcer.RequireReleaseDeps executed') -assert buildLog.contains( '[INFO] Rule 5: org.apache.maven.plugins.enforcer.RequireUpperBoundDeps executed') +assert buildLog.contains( '[INFO] Rule 1: org.apache.maven.enforcer.rules.dependency.BanTransitiveDependencies executed' ) +assert buildLog.contains( '[INFO] Rule 2: org.apache.maven.enforcer.rules.dependency.BannedDependencies executed' ) +assert buildLog.contains( '[INFO] Rule 3: org.apache.maven.enforcer.rules.dependency.DependencyConvergence executed') +assert buildLog.contains( '[INFO] Rule 4: org.apache.maven.enforcer.rules.dependency.RequireReleaseDeps executed') +assert buildLog.contains( '[INFO] Rule 5: org.apache.maven.enforcer.rules.dependency.RequireUpperBoundDeps executed') diff --git a/maven-enforcer-plugin/src/it/projects/require-upper-bound-dependencies-managed_failure/verify.groovy b/maven-enforcer-plugin/src/it/projects/require-upper-bound-dependencies-managed_failure/verify.groovy index 35b2b664..94c0cac9 100644 --- a/maven-enforcer-plugin/src/it/projects/require-upper-bound-dependencies-managed_failure/verify.groovy +++ b/maven-enforcer-plugin/src/it/projects/require-upper-bound-dependencies-managed_failure/verify.groovy @@ -18,7 +18,7 @@ */ def LS = System.getProperty( "line.separator" ) File buildLog = new File( basedir, 'build.log' ) -assert buildLog.text.contains( 'Rule 0: org.apache.maven.plugins.enforcer.RequireUpperBoundDeps failed with message:' ) +assert buildLog.text.contains( 'Rule 0: org.apache.maven.enforcer.rules.dependency.RequireUpperBoundDeps failed with message:' ) def message = 'Failed while enforcing RequireUpperBoundDeps. The error(s) are [' + LS+ 'Require upper bound dependencies error for org.apache.maven.plugins.enforcer.its:menforcer146-x:1.1 paths to dependency are:' + LS+ diff --git a/maven-enforcer-plugin/src/it/projects/require-upper-bound-dependencies-unique_failure/verify.groovy b/maven-enforcer-plugin/src/it/projects/require-upper-bound-dependencies-unique_failure/verify.groovy index d65ff008..21b9ba5a 100644 --- a/maven-enforcer-plugin/src/it/projects/require-upper-bound-dependencies-unique_failure/verify.groovy +++ b/maven-enforcer-plugin/src/it/projects/require-upper-bound-dependencies-unique_failure/verify.groovy @@ -17,5 +17,5 @@ * under the License. */ File buildLog = new File( basedir, 'build.log' ) -assert buildLog.text.contains( 'Rule 0: org.apache.maven.plugins.enforcer.RequireUpperBoundDeps failed with message:' ) +assert buildLog.text.contains( 'Rule 0: org.apache.maven.enforcer.rules.dependency.RequireUpperBoundDeps failed with message:' ) assert buildLog.text.contains( 'Require upper bound dependencies error for org.apache.maven.plugins.enforcer.its:menforcer134_model:1.0-20130423.042904-7222 paths to dependency are:' ) diff --git a/maven-enforcer-plugin/src/it/projects/require-upper-bound-deps_failure/verify.groovy b/maven-enforcer-plugin/src/it/projects/require-upper-bound-deps_failure/verify.groovy index 38bb648c..8ad1ba3c 100644 --- a/maven-enforcer-plugin/src/it/projects/require-upper-bound-deps_failure/verify.groovy +++ b/maven-enforcer-plugin/src/it/projects/require-upper-bound-deps_failure/verify.groovy @@ -19,7 +19,7 @@ def LS = System.getProperty( "line.separator" ) File buildLog = new File( basedir, 'build.log' ) -assert buildLog.text.contains( 'Rule 0: org.apache.maven.plugins.enforcer.RequireUpperBoundDeps failed with message:' ) +assert buildLog.text.contains( 'Rule 0: org.apache.maven.enforcer.rules.dependency.RequireUpperBoundDeps failed with message:' ) def message = 'Require upper bound dependencies error for org.apache.maven.plugins.enforcer.its:menforcer128_api:1.4.0 paths to dependency are:'+LS+ '+-org.apache.maven.plugins.enforcer.its:menforcer128:1.0-SNAPSHOT'+LS+ diff --git a/maven-enforcer-plugin/src/it/projects/require-upper-bound-deps_failure_show_scopes/verify.groovy b/maven-enforcer-plugin/src/it/projects/require-upper-bound-deps_failure_show_scopes/verify.groovy index 18eb75d9..42ca1ab0 100644 --- a/maven-enforcer-plugin/src/it/projects/require-upper-bound-deps_failure_show_scopes/verify.groovy +++ b/maven-enforcer-plugin/src/it/projects/require-upper-bound-deps_failure_show_scopes/verify.groovy @@ -19,7 +19,7 @@ def LS = System.getProperty( "line.separator" ) File buildLog = new File( basedir, 'build.log' ) -assert buildLog.text.contains( 'Rule 0: org.apache.maven.plugins.enforcer.RequireUpperBoundDeps failed with message:' ) +assert buildLog.text.contains( 'Rule 0: org.apache.maven.enforcer.rules.dependency.RequireUpperBoundDeps failed with message:' ) def message = 'Require upper bound dependencies error for org.apache.maven.plugins.enforcer.its:menforcer128_api:1.4.0 [runtime] paths to dependency are:'+LS+ '+-org.apache.maven.plugins.enforcer.its:menforcer313:1.0-SNAPSHOT'+LS+ diff --git a/maven-enforcer-plugin/src/it/projects/require-upper-bound-deps_includes/verify.groovy b/maven-enforcer-plugin/src/it/projects/require-upper-bound-deps_includes/verify.groovy index db22ccff..e74bee32 100644 --- a/maven-enforcer-plugin/src/it/projects/require-upper-bound-deps_includes/verify.groovy +++ b/maven-enforcer-plugin/src/it/projects/require-upper-bound-deps_includes/verify.groovy @@ -19,7 +19,7 @@ def LS = System.getProperty( "line.separator" ) File buildLog = new File( basedir, 'build.log' ) -assert buildLog.text.contains( 'Rule 0: org.apache.maven.plugins.enforcer.RequireUpperBoundDeps failed with message:' ) +assert buildLog.text.contains( 'Rule 0: org.apache.maven.enforcer.rules.dependency.RequireUpperBoundDeps failed with message:' ) def message = 'Require upper bound dependencies error for org.apache.maven.plugins.enforcer.its:menforcer128_api:1.4.0 paths to dependency are:'+LS+ '+-org.apache.maven.plugins.enforcer.its:menforcer128:1.0-SNAPSHOT'+LS+