java - 将编译时依赖项写入文件

标签 java groovy gradle

我正在尝试检查项目的依赖项并将其写入自定义文件中。

我熟悉使用“jar”插件创建 fat 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
    }

}

最佳答案

Configuration从configuration.runtime返回的对象已经是FileCollection接口(interface),因此您可以轻松地对其进行迭代。这就是为什么你的 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 在下面的评论中所建议的,您可以对此任务进行一些进一步的优化,特别是使您的文件成为任务的输出,这样,如果任务的输入没有更改,您的文件不需要重新创建,并且作业将跳过。所以上面的内容相当原始。

关于java - 将编译时依赖项写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31410888/

相关文章:

java - 在 Elastic Beanstalk 上设置 G1GC 时出错

java - 为什么java在我的资源文件夹中找不到该文件?

java - 无法在子类中创建返回类型为 Object 的方法

java - 从字符串映射中删除几个元素到特定键的列表

java - JsonParser 中的 toXML 在哪里,为什么该方法不可用?

Grails 验证错误从服务到 Controller 消失

java - Groovy AntBuilder - 指定 Java 临时目录

groovy - 在groovy中,如何动态调用类的静态方法?

android - 如何使用 Android gradle 插件 0.10.0 或更高版本获取 jacoco 覆盖率报告?

android - 运行单元测试时没有可用资源