我正在尝试检查项目的依赖项并将其写入自定义文件中。
我熟悉使用“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/