从依赖项中提取特定JAR

时间:2012-07-02 16:29:28

标签: gradle

我是新手,但很快就学会了。我需要从logback中获取一些特定的JAR到我的发布任务中的新目录中。依赖关系正在解决,但我无法弄清楚在发布任务中如何将logback-core-1.0.6.jar和logback-access-1.0.6.jar解压缩到名为'lib / ext的目录中”。以下是我的build.gradle的相关摘录。

dependencies {
    ...
    compile 'org.slf4j:slf4j-api:1.6.4'
    compile 'ch.qos.logback:logback-core:1.0.6'
    compile 'ch.qos.logback:logback-classic:1.0.6'
    runtime 'ch.qos.logback:logback-access:1.0.6'
    ...
}
...
task release(type: Tar, dependsOn: war) {
    extension = "tar.gz"
    classifier = project.classifier
    compression = Compression.GZIP

    into('lib') {
        from configurations.release.files
        from configurations.providedCompile.files
    }

    into('lib/ext') {
        // TODO:  Right here I want to extract just logback-core-1.0.6.jar and logback-access-1.0.6.jar
    }
    ...
}

如何迭代依赖项以找到这些特定文件并将它们放入由into('lib / ext')创建的lib / ext目录中?

2 个答案:

答案 0 :(得分:21)

Configurations只是(懒惰)集合。您可以迭代它们,过滤它们等。请注意,您通常只希望在构建的执行阶段中执行此操作,而不是在配置阶段中执行此操作。下面的代码通过使用惰性FileCollection.filter()方法实现了这一点。另一种方法是将闭包传递给Tar.from()方法。

task release(type: Tar, dependsOn: war) {
    ...
    into('lib/ext') {
        from findJar('logback-core') 
        from findJar('logback-access')
    }
}

def findJar(prefix) { 
    configurations.runtime.filter { it.name.startsWith(prefix) }
}

答案 1 :(得分:9)

接受的答案将Configuration过滤为FileCollection并不值得,因此在集合中您只能访问文件的属性。如果要过滤依赖项本身(在组,名称或版本上)而不是在缓存中的文件名,那么您可以使用以下内容:

task copyToLib(type: Copy) {
  from findJarsByGroup(configurations.compile, 'org.apache.avro')
  into "$buildSrc/lib"
}

def findJarsByGroup(Configuration config, groupName) {
  configurations.compile.files { it.group.equals(groupName) }
}

files接受一个dependencySpecClosure,它只是Dependency上的过滤函数,请参阅:https://gradle.org/docs/current/javadoc/org/gradle/api/artifacts/Dependency.html

相关问题