How can I get a dependency's version in the current pom.xml for maven-enforcer-plugin?

1.1k views Asked by At

I'm trying to write an maven-enforcer rule, which checks that that project uses dependency management.

But I've got trouble to get the version which is written in the current project's pom.xml. I thought DependencyNode#getPremanagedVersion() would provide it, but it looks like it's returning a version which is set by a dependency (i.e. log4j is set in jbossall-client).

How can I get a dependency's version in the current pom.xml?

package org.example;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactCollector;
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.project.MavenProject;
import org.apache.maven.shared.dependency.tree.DependencyNode;
import org.apache.maven.shared.dependency.tree.DependencyTreeBuilder;
import org.opencredo.maven.plugins.enforcer.utils.DefaultDependencyTreePrinter;

import com.oneandone.access.preclearing.AbstractNonCacheableEnforcerRule;

public class ForceDependencyManagement extends AbstractNonCacheableEnforcerRule implements EnforcerRule {
    private String message = "";

    private MavenProject project;
    private ArtifactRepository localRepository;
    private ArtifactFactory artifactFactory;
    private ArtifactMetadataSource artifactMetadataSource;
    private ArtifactCollector artifactCollector;
    private DependencyTreeBuilder dependencyTreeBuilder;

    private void init(EnforcerRuleHelper helper) throws EnforcerRuleException {
        try {
            project = (MavenProject) helper.evaluate("${project}");
            localRepository = (ArtifactRepository) helper.evaluate("${localRepository}");
            artifactFactory = (ArtifactFactory) helper.getComponent(ArtifactFactory.class);
            artifactCollector = (ArtifactCollector) helper.getComponent(ArtifactCollector.class);
            artifactMetadataSource = (ArtifactMetadataSource) helper.getComponent(ArtifactMetadataSource.class);
            dependencyTreeBuilder = (DependencyTreeBuilder) helper.getComponent(DependencyTreeBuilder.class);
        } catch (Exception eee) {
            throw new EnforcerRuleException("Unable to retrieve the rule dependencies: ", eee);
        }
    }

    public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException {
        init(helper);

        DependencyNode rootNode = buildDependencyTree();
        if (rootNode != null) {
            Set found = new HashSet();

            Iterator iter = rootNode.iterator();
            System.out.println("Dependencies: ");
            while (iter.hasNext()) {
                DependencyNode node = (DependencyNode) iter.next();
                if (StringUtils.isNotEmpty(node.getPremanagedVersion())) {
                    found.add(node);
                }
            }

            if (found.size() > 0) {
                fail(found);
            }
        }

    }

    protected DependencyNode buildDependencyTree() {
        try {
            DependencyNode rootNode =
                    dependencyTreeBuilder.buildDependencyTree(project, localRepository, artifactFactory,
                            artifactMetadataSource, null, artifactCollector);
            return rootNode;
        } catch (Exception e) {
            throw new RuntimeException("Failed to build dependency tree", e);
        }
    }

    private void fail(Set found) throws EnforcerRuleException {
        Iterator iter;
        StringBuffer fullMessage = new StringBuffer();
        if (StringUtils.isNotEmpty(message)) {
            fullMessage.append(message);
        } else {
            fullMessage.append("Found artifact without dependency management:");
        }
        fullMessage.append("\n");

        iter = found.iterator();
        while (iter.hasNext()) {
            DependencyNode node = (DependencyNode) iter.next();
            Artifact artifact = node.getArtifact();
            fullMessage.append("  " + artifact.getGroupId() + ":" + artifact.getArtifactId() + " is set to version "
                    + node.getPremanagedVersion() + "\n");
            getTreePrinter().printDependencyTree(fullMessage, artifact, 4);
        }

        throw new EnforcerRuleException(fullMessage.toString());
    }

    private DefaultDependencyTreePrinter getTreePrinter() {
        return new DefaultDependencyTreePrinter(project, localRepository, artifactFactory, artifactMetadataSource,
                artifactCollector, dependencyTreeBuilder);
    }

    public boolean isCacheable() {
        return false;
    }

    public String getCacheId() {
        return null;
    }

    public boolean isResultValid(EnforcerRule cachedRule) {
        return false;
    }

}
1

There are 1 answers

0
Matt McClellan On

This should do it

MavenProject project = (MavenProject) helper.evaluate("${project}");
List dependencies = project.getDependencies();

From there just iterate throught the list of dependencies and call .getVersion()

for (int i = 0; i < project.getDependencies().size(); i++) {
    String version = project.getDependencies().get(i).getVersion();
}

You can also get to the dependency management info from the project object