如何从 Gradle Maven Publishing 插件构建的 POM 中排除依赖项?

How can I exclude a dependency from a POM built by the Gradle Maven Publishing plugin?

我的 build.gradle 中有以下依赖项:

dependencies {
    compile 'org.antlr:antlr4-runtime:4.5.1'
    compile 'org.slf4j:slf4j-api:1.7.12'
    antlr "org.antlr:antlr4:4.5.1"
    testCompile group: 'junit', name: 'junit', version: '4.11'
    testCompile 'org.spockframework:spock-core:1.0-groovy-2.4'
    testCompile 'org.codehaus.groovy:groovy-all:2.4.4'
    testCompile 'cglib:cglib-nodep:3.1'
    testCompile 'org.objenesis:objenesis:2.1'
}

当我使用 Maven 发布插件发布我的库时,它包括 ANTLR 运行时和编译时 JAR 作为 generated POM:

中的依赖项
<dependencies>
  <dependency>                    <!-- runtime artifact -->
    <groupId>org.antlr</groupId>
    <artifactId>antlr4-runtime</artifactId>
    <version>4.5.1</version>
    <scope>runtime</scope>
  </dependency>
  <dependency>                    <!-- compile time artifact, should not be included -->
    <groupId>org.antlr</groupId>
    <artifactId>antlr4</artifactId>
    <version>4.5.1</version>
    <scope>runtime</scope>
  </dependency>
</dependencies>

我只想将运行时库包含在此 POM 中。

罪魁祸首是 antlr 依赖项:如果我删除此行,生成的 POM 将不具有编译时依赖项。但是,构建失败。

试试 gradle-fury。它肯定会处理排除项,而且我很确定生成的 poms 中只包含已知配置。它还有一些代码来确保不存在范围冲突的重复条目(找出解决方案非常痛苦)

https://github.com/gradle-fury/gradle-fury

免责声明,我正在努力

@RaGe 建议使用 pom.withXml 我能够使用这个 hackery 来消除额外的依赖。

pom.withXml {
  Node pomNode = asNode()
  pomNode.dependencies.'*'.findAll() {
    it.artifactId.text() == 'antlr4'
  }.each() {
    it.parent().remove(it)
  }
}

之前:

<dependencies>
    <dependency>
      <groupId>org.antlr</groupId>
      <artifactId>antlr4-runtime</artifactId>
      <version>4.5.1</version>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>org.antlr</groupId>
      <artifactId>antlr4</artifactId>
      <version>4.5.1</version>
      <scope>runtime</scope>
    </dependency>
</dependencies>

之后:

<dependencies>
    <dependency>
      <groupId>org.antlr</groupId>
      <artifactId>antlr4-runtime</artifactId>
      <version>4.5.1</version>
      <scope>runtime</scope>
    </dependency>
</dependencies>

一些更多的链接来解释这个问题: