Skip to content

Commit

Permalink
Use new Enforcer Api
Browse files Browse the repository at this point in the history
  • Loading branch information
slawekjaranowski committed Feb 26, 2024
1 parent 3a97c36 commit ecd15b0
Show file tree
Hide file tree
Showing 6 changed files with 454 additions and 354 deletions.
1 change: 1 addition & 0 deletions versions-enforcer/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
<description>Enforcer rules using Versions Maven Plugin</description>

<properties>
<!-- used in documentations -->
<maven-enforcer-plugin-version>${maven-enforcer-plugin.version}</maven-enforcer-plugin-version>
</properties>

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package org.apache.maven.plugins.enforcer;
package org.codehaus.mojo.versions.enforcer;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
Expand All @@ -18,20 +18,21 @@
* under the License.
*/

import javax.inject.Inject;
import javax.inject.Named;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;

import org.apache.maven.artifact.versioning.ArtifactVersion;
import org.apache.maven.enforcer.rule.api.EnforcerLevel;
import org.apache.maven.enforcer.rule.api.EnforcerRule;
import org.apache.maven.enforcer.rule.api.EnforcerRule2;
import org.apache.maven.enforcer.rule.api.AbstractEnforcerRule;
import org.apache.maven.enforcer.rule.api.EnforcerRuleError;
import org.apache.maven.enforcer.rule.api.EnforcerRuleException;
import org.apache.maven.enforcer.rule.api.EnforcerRuleHelper;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Dependency;
import org.apache.maven.plugin.MojoExecution;
Expand All @@ -46,8 +47,6 @@
import org.codehaus.mojo.versions.api.VersionsHelper;
import org.codehaus.mojo.versions.model.RuleSet;
import org.codehaus.mojo.versions.utils.DependencyComparator;
import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;

import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
Expand All @@ -62,7 +61,8 @@
import static org.codehaus.mojo.versions.utils.MavenProjectUtils.extractDependenciesFromPlugins;
import static org.codehaus.mojo.versions.utils.MavenProjectUtils.extractPluginDependenciesFromPluginsInPluginManagement;

public class MaxDependencyUpdates implements EnforcerRule2 {
@Named("maxDependencyUpdates")
public class MaxDependencyUpdates extends AbstractEnforcerRule {
/**
* Maximum allowed number of updates.
*
Expand Down Expand Up @@ -232,7 +232,7 @@ public class MaxDependencyUpdates implements EnforcerRule2 {
* version numbers. The URI could be either a Wagon URI or a classpath URI
* (e.g. <code>classpath:///package/sub/package/rules.xml</code>).
*
* 2.14.0
* @since 2.14.0
*/
private String rulesUri;

Expand All @@ -254,81 +254,78 @@ public class MaxDependencyUpdates implements EnforcerRule2 {
*/
protected boolean allowSnapshots;

/**
* Retrieves the maven project from metadata
* @param ruleHelper EnforcerRuleHelper object
* @return maven project
*/
private static MavenProject getMavenProject(EnforcerRuleHelper ruleHelper) {
try {
return (MavenProject) ruleHelper.evaluate("${project}");
} catch (ExpressionEvaluationException e) {
throw new RuntimeException("Cannot evaluate project metadata", e);
}
private final MavenProject project;

private final RepositorySystem repositorySystem;

private final org.eclipse.aether.RepositorySystem aetherRepositorySystem;

private final Map<String, Wagon> wagonMap;

private final MavenSession mavenSession;

private final MojoExecution mojoExecution;

@Inject
public MaxDependencyUpdates(
MavenProject project,
RepositorySystem repositorySystem,
org.eclipse.aether.RepositorySystem aetherRepositorySystem,
Map<String, Wagon> wagonMap,
MavenSession mavenSession,
MojoExecution mojoExecution) {
this.project = project;
this.repositorySystem = repositorySystem;
this.aetherRepositorySystem = aetherRepositorySystem;
this.wagonMap = wagonMap;
this.mavenSession = mavenSession;
this.mojoExecution = mojoExecution;
}

/**
* Creates the VersionsHelper object
* @param ruleHelper EnforcerRuleHelper object
* @return VersionsHelper object
*/
@SuppressWarnings("unchecked")
private static VersionsHelper createVersionsHelper(
EnforcerRuleHelper ruleHelper, String serverId, String rulesUri, RuleSet ruleSet) {
private VersionsHelper createVersionsHelper(String serverId, String rulesUri, RuleSet ruleSet)
throws EnforcerRuleError {
try {
return new DefaultVersionsHelper.Builder()
.withRepositorySystem(ruleHelper.getComponent(RepositorySystem.class))
.withAetherRepositorySystem(ruleHelper.getComponent(org.eclipse.aether.RepositorySystem.class))
.withWagonMap(ruleHelper.getComponentMap(Wagon.class.getName()).entrySet().stream()
.filter(e -> e.getValue() instanceof Wagon)
.collect(HashMap::new, (m, e) -> m.put(e.getKey(), (Wagon) e.getValue()), HashMap::putAll))
.withRepositorySystem(repositorySystem)
.withAetherRepositorySystem(aetherRepositorySystem)
.withWagonMap(wagonMap)
.withServerId(serverId)
.withRulesUri(rulesUri)
.withRuleSet(ruleSet)
.withIgnoredVersions(null)
.withLog(ruleHelper.getLog())
.withMavenSession((MavenSession) ruleHelper.evaluate("${session}"))
.withMojoExecution((MojoExecution) ruleHelper.evaluate("${mojoExecution}"))
.withLog(new PluginLogWrapper(getLog()))
.withMavenSession(mavenSession)
.withMojoExecution(mojoExecution)
.build();
} catch (ExpressionEvaluationException e) {
throw new RuntimeException("Cannot evaluate project metadata", e);
} catch (ComponentLookupException | MojoExecutionException e) {
throw new RuntimeException("Cannot resolve dependency", e);
} catch (MojoExecutionException e) {
throw new EnforcerRuleError("Cannot resolve dependency", e);
}
}

@Override
public boolean isCacheable() {
return false;
}

@Override
public boolean isResultValid(EnforcerRule enforcerRule) {
return false;
}
public void execute() throws EnforcerRuleException {

@Override
public String getCacheId() {
return "Does not matter as not cacheable";
}
PluginLogWrapper pluginLog = new PluginLogWrapper(getLog());

@Override
public void execute(EnforcerRuleHelper ruleHelper) throws EnforcerRuleException {
VersionsHelper versionsHelper =
createVersionsHelper(ruleHelper, serverId != null ? serverId : "serverId", rulesUri, ruleSet);
MavenProject project = getMavenProject(ruleHelper);
createVersionsHelper(serverId != null ? serverId : "serverId", rulesUri, ruleSet);

Set<Dependency> dependencies = new TreeSet<>(DependencyComparator.INSTANCE);
if (processDependencyManagement) {
try {
dependencies.addAll(filterDependencies(
extractDependenciesFromDependencyManagement(
project, processDependencyManagementTransitive, ruleHelper.getLog()),
project, processDependencyManagementTransitive, pluginLog),
dependencyManagementIncludes,
dependencyManagementExcludes,
"Dependency Management",
ruleHelper.getLog()));
pluginLog));
} catch (VersionRetrievalException e) {
throw new EnforcerRuleException(e.getMessage());
throw new EnforcerRuleError(e.getMessage());
}
}
if (processPluginDependencies) {
Expand All @@ -337,23 +334,19 @@ public void execute(EnforcerRuleHelper ruleHelper) throws EnforcerRuleException
pluginDependencyIncludes,
pluginDependencyExcludes,
"Plugin Dependencies",
ruleHelper.getLog()));
pluginLog));
}
if (processPluginDependenciesInPluginManagement) {
dependencies.addAll(filterDependencies(
extractPluginDependenciesFromPluginsInPluginManagement(project),
pluginManagementDependencyIncludes,
pluginManagementDependencyExcludes,
"Plugin Management Dependencies",
ruleHelper.getLog()));
pluginLog));
}
if (processDependencies) {
dependencies.addAll(filterDependencies(
project.getDependencies(),
dependencyIncludes,
dependencyExcludes,
"Dependencies",
ruleHelper.getLog()));
project.getDependencies(), dependencyIncludes, dependencyExcludes, "Dependencies", pluginLog));
}
try {
Optional<Segment> ignoredSegment = ignoreSubIncrementalUpdates
Expand All @@ -379,13 +372,7 @@ public void execute(EnforcerRuleHelper ruleHelper) throws EnforcerRuleException
.collect(Collectors.joining(", ")));
}
} catch (VersionRetrievalException e) {
throw new RuntimeException(e.getMessage(), e);
throw new EnforcerRuleError(e);
}
}

@Override
public EnforcerLevel getLevel() {
// all reported items should be treated as errors
return EnforcerLevel.ERROR;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
package org.codehaus.mojo.versions.enforcer;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import org.apache.maven.enforcer.rule.api.EnforcerLogger;
import org.apache.maven.plugin.logging.Log;

/**
* Wrapper used to pass {@link EnforcerLogger} as Maven plugin {@link Log}.
*/
class PluginLogWrapper implements Log {

private final EnforcerLogger logger;

PluginLogWrapper(EnforcerLogger logger) {
this.logger = logger;
}

@Override
public boolean isDebugEnabled() {
return logger.isDebugEnabled();
}

@Override
public void debug(CharSequence charSequence) {
logger.debug(charSequence);
}

@Override
public void debug(CharSequence charSequence, Throwable throwable) {
logger.debug(charSequence + throwableToString(throwable));
}

@Override
public void debug(Throwable throwable) {
logger.debug(throwableToString(throwable));
}

@Override
public boolean isInfoEnabled() {
return logger.isInfoEnabled();
}

@Override
public void info(CharSequence charSequence) {
logger.info(charSequence);
}

@Override
public void info(CharSequence charSequence, Throwable throwable) {

logger.info(charSequence + throwableToString(throwable));
}

@Override
public void info(Throwable throwable) {
logger.info(throwableToString(throwable));
}

@Override
public boolean isWarnEnabled() {
return logger.isWarnEnabled();
}

@Override
public void warn(CharSequence charSequence) {
logger.warn(charSequence);
}

@Override
public void warn(CharSequence charSequence, Throwable throwable) {
logger.warn(charSequence + throwableToString(throwable));
}

@Override
public void warn(Throwable throwable) {
logger.warn(throwableToString(throwable));
}

@Override
public boolean isErrorEnabled() {
return logger.isErrorEnabled();
}

@Override
public void error(CharSequence charSequence) {
logger.error(charSequence);
}

@Override
public void error(CharSequence charSequence, Throwable throwable) {
logger.error(charSequence + throwableToString(throwable));
}

@Override
public void error(Throwable throwable) {
logger.error(throwableToString(throwable));
}

private String throwableToString(Throwable throwable) {
if (throwable != null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
throwable.printStackTrace(new PrintStream(stream));
return System.lineSeparator() + stream;
}
return "";
}
}
Loading

0 comments on commit ecd15b0

Please sign in to comment.