编写编译时间依赖项到文件

时间:2015-07-14 15:26:21

标签: java groovy gradle

我试图浏览项目的依赖项并将其写入自定义文件中。

我熟悉你制作胖罐的方式,使用' jar'插件,但自定义任务中的类似方法似乎不起作用。

我尝试过的一些代码。

// First way I tried to do it. 
task customTask(){
    File manifest = new File('file.txt')
    manifest << 'Some Text\n'
    manifest << 'Dependencies:'

    configurations.runtime.collect{ manifest << it.name}

}

// The second way I tried to do it. 
task manifest(){
    File manifest = new File('file.txt')
    manifest << 'Header\n'
    manifest << 'Dependencies:'
    FileTree tree = fileTree(dir: configurations.compile, include: '**/*.jar')
    tree.each {File file ->
        manifest << file
    }

}

1 个答案:

答案 0 :(得分:3)

从configuration.runtime返回的Configuration对象已经是FileCollection接口,因此您可以轻松地对其进行迭代。这就是你的fileTree(dir:xxx)不起作用的原因,因为它采用目录路径并创建文件列表,但配置已经是一个。

以下对我有用:

apply plugin: 'groovy'
dependencies {
    // compile gradleApi()
    compile 'junit:junit:4.11'
}

repositories {
    mavenCentral()
}

task t1 << {
    def manifest = project.file('file.txt')
    manifest.delete()
    manifest << 'Dependencies:\n'

    // you can use it.path here if you need full path to jar
    configurations.runtime.each { manifest << it.name + "\n"}

    // also configurations.compile.each works here
}

输出以下内容:

Dependencies:
junit-4.11.jar
hamcrest-core-1.3.jar

取消注释依赖项中的行compile groovyApi(),它会吸引更多的jar。

一般情况下,我总是使用project.file()(您可以使用file()但我喜欢在项目方法上详细说明)来创建文件对象,而不是new File(foo)

正如Peter Ledbrook在下面的评论中所建议的那样,你可以对这项任务进行一些进一步的优化,特别是在使你的文件成为任务的输出时,这样如果任务的输入没有改变,你的文件不需要重新创建,作业将跳过。所以上面是相当原始的。

相关问题