10

我有一个 Gradle 构建,它可以生成我的产品的主要可交付工件(安装程序)。对此进行建模的 Gradle 项目在不同的配置中具有许多不同的依赖项。其中许多依赖项都依赖于外部模块的默认配置,其中一些模块的testResults配置包含测试任务的(压缩)结果。

重要的是,所有依赖项的测试结果(如果存在)作为主要产品构建的工件发布(用作测试发生并成功的证据)。如果它们不存在,这不是问题。

我试图通过迭代产品构建的所有配置、迭代每个配置中的依赖项并在testResults模块的配置上添加以编程方式创建的依赖项(在为此目的创建的新配置中)来做到这一点。

换句话说,我创建这样的依赖项:

def processDependencyForTests( Dependency dependency ) {

    def testResultsDependency = [
      'group' : dependency.group,
      'name' : dependency.name,
      'version' : dependency.version,
      'configuration' : 'testResults'
      ]

    project.dependencies.add 'allTestResults', testResultsDependency

这可以很好地填充该配置,但是当然,当我尝试使用它做任何事情时,它会在我第一次遇到对实际上没有配置的模块的依赖时失败testResults

   def resolvedConfiguration = configurations.allTestResults.resolvedConfiguration

结果如下:

Build file 'C:\myproduct\build.gradle' line: 353

* What went wrong:
Execution failed for task ':myproduct:createBuildRecord'.
> Could not resolve all dependencies for configuration ':myproduct:allTestResults'.
   > Module version group:mygroup, module:myproduct, version:1.2.3.4, configuration:allTestResults declares a dependency on configuration 'testResults' which is not declared in the module descriptor for group:mygroup, module:mymodule, version:1.0

以声明的方式显式列出依赖项并不实际,因为我希望它们源自“产品项目具有的任何真正的依赖项”。

如何确保这种预期的缺失配置不会破坏我的构建?我认为与宽松的配置有关的问题可能是答案,但我什至还没有走到这一步(据我所知,我需要获得ResolvedConfiguration第一个)。或者,如果我这样做的方式很疯狂,那么实现这一点的更自然的 Gradle 习语是什么?

4

2 回答 2

2

在引用它之前,您需要检查配置是否存在。在这种情况下,gradle DSL 文档是你的朋友。事实上,gradle 项目是我合作过的文档最完整的开源项目之一。

在这里,您会发现它configurations只是一个configuration对象容器。它们分别是ConfigurationContainerConfiguration的实例。知道了这一点,您需要做的就是检查容器是否configurations包含一个configuration名为“testResults”的容器。

这可以通过以下代码实现:

if (configurations.find { it.name == 'testResults' }) {
    // do your stuff
}
于 2013-03-13T22:41:59.487 回答
0

似乎暗示Dependency传递给您的processDependencyForTests方法的实例是多模块构建中的模块依赖项。

在这种情况下,您可以将它们强制转换为ProjectDependency,它具有dependencyProject允许您访问该Project依赖项的对象的属性。从那里您可以depProject.configurations.findByName用来测试配置是否存在。

类似于以下内容:

def processDependencyForTests( Dependency dependency ) {
  if( dependency instanceof ProjectDependency ) {
    ProjectDependency projDep = (ProjectDependency) dependency
    if( projDep.dependencyProject.configurations.findByName( 'testResults' ) ) {
      def testResultsDependency = [
        'group' : dependency.group,
        'name' : dependency.name,
        'version' : dependency.version,
        'configuration' : 'testResults'
      ]
      project.dependencies.add 'allTestResults', testResultsDependency
    }
  }

高温高压

于 2015-07-08T15:34:12.950 回答