1

假设我的 gradle 构建脚本中有以下内容:

configurations.all {
  resolutionStrategy {

    failOnVersionConflict()

    force 'com.google.guava:guava:18.0'
    }
}

如果找到多个版本的 jar,这将失败,但 guava 除外,它将强制为 18.0 版本。

现在让我们想象一下,我想拥有failOnVersionConflict()所有外部 jar,并被迫使用 force 子句(所以我知道我在做什么),但我想对某些特定组使用默认的 resolutionStrategy (最新版本),比如com.mycompany.

这样的事情可能吗?

我正在查看此文档页面:

https://gradle.org/docs/current/dsl/org.gradle.api.artifacts.ResolutionStrategy.html

4

1 回答 1

3

我找到了自己的答案……但这涉及到一些“黑客行为”……但是,毕竟,这正是 gradle 提供的……

def dependencyErrors = 0

configurations.all {
  resolutionStrategy {

    def thirdPartyPackages = [:]
    def forced = [ 
        'com.google.guava:guava' : '18.0'
        //Here all forced dependencies...
    ]


     eachDependency { DependencyResolveDetails details ->


          if (!details.requested.group.startsWith('com.mycompany')) {

                def key = details.requested.group + ":" + details.requested.name
                if(!thirdPartyPackages.containsKey(key)) {
                    if(forced.containsKey(key)) {
                        details.useVersion forced.get(key)
                    }                   
                    else {
                        thirdPartyPackages.put(key, details.requested.version);
                    }
                }
                else {
                    def existing =  thirdPartyPackages.get(key);
                    if(existing != details.requested.version) {
                        logger.error "Conflicting versions for [$key]"
                        logger.error "    [$existing]"
                        logger.error "    [$details.requested.version]"
                        dependencyErrors++
                    }
                }
          }
      }

  }
}

myTask.doFirst {
  //here it might also be doLast, or whatever you need. I just put it before a war task, but it might depend on each need. 
  if(dependencyErrors > 0) {
    ant.fail 'There are ' + dependencyErrors + ' conflicting jar versions in the build.'
  }
}
于 2015-03-13T11:43:00.707 回答