如何在当前 pom.xml 中获取 maven-enforcer-plugin 的依赖项版本?

发布于 2024-12-09 19:27:59 字数 4962 浏览 0 评论 0原文

我正在尝试编写一个 maven-enforcer 规则,该规则检查该项目是否使用依赖项管理。

但我在获取当前项目的 pom.xml 中编写的版本时遇到了麻烦。我认为 DependencyNode#getPremanagementVersion() 会提供它,但看起来它返回的是由依赖项设置的版本(即 log4j 在 jbossall-client 中设置)。

如何获取当前 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;
    }

}

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;
    }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ヤ经典坏疍 2024-12-16 19:27:59

应该可以

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

从那里迭代依赖项列表并调用 .getVersion()

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

您还可以从项目对象获取依赖项管理信息

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文