Gradle 复制任务:Ant 到 gradle 迁移

Gradle Copy task: Ant to gradle migration

我是 gradle 的新手,正在将 ant build.xml 脚本迁移到 gradle。通常复制任务相当简单直接,但我遇到了这个复杂的小复制任务(可能也很简单),它启用了详细信息和文件集。我可以知道如何将此 ant 代码转换为 gradle 任务吗?

<copy todir="client" verbose="true">
        <fileset dir="${build.classes}">
        <include name="com/corp/domain/**" />                   
      </fileset>
   </copy>

Gradle 到目前为止我尝试写的任务是

task copyDocs(type: Copy) {
  from 'dist'
  include "com/corp/domain/**"
  into 'client'
}

我需要知道 fileset 和 verbose 如何进入画面以使其成为完美的迁移任务

@ronypatil,下面的代码可以作为你解决问题的一个很好的参考:

task copyDocs(type: Copy) {
    FileTree tree = fileTree("dist")
    tree.include "com/corp/domain/**"

    File toPath = file("client")

    tree.each { File file ->
        from file
        into toPath
        println "copy $file into $toPath"
    }
}

您的 Gradle 任务几乎已经完成了所有工作。一个 <fileset> in Ant is a group of files. Using dir=, you can start in one directory and include or exclude a subset of all files in this directory. This behaviour is already implemented by the Gradle Copy task, because it implements the CopySpec 界面。因此,对于一个 Ant <fileset>,您可以使用 Copy 任务及其方法,就像您在示例中所做的那样:

task copyDocs(type: Copy) {
    from 'path/to/dir'
    include 'com/corp/domain/**'
    into 'client'
}

如果您需要使用多个 <fileset> 元素,您可以为每个元素添加一个子元素 CopySpec,例如通过使用 from 方法后跟闭包。此闭包中的配置将仅适用于此目录中的文件,就像配置单个 <fileset>:

task copyDocs(type: Copy) {
    from('dir1') {
        include 'foo/bar'
    }
    from('dir2') {
        exclude 'bar/foo'
    }
    into 'dir3'
}

${build.classes} 指的是 Ant 属性。由于 Gradle 基于 Groovy,您可以在不同的地方和方式定义 属性(例如 extra properties),但请注意 build 是名称一个任务,它存在于几乎所有 Gradle 构建脚本中,因此直接使用 build.classes 可能会在 build 任务的范围内查找 属性:

task copyDocs(type: Copy) {
    // if you defined the property before
    from my.build.classes
    include 'com/corp/domain/**'
    into 'client'
}

verbose 属性仅定义是否所有文件复制操作都应记录在控制台上。 Gradle 不支持通过简单选项进行文件日志记录,因此我们需要自己实现它。幸运的是,Gradle 提供了 eachFile 方法。我们可以传递一个闭包,它会为每个复制的文件调用并携带一个 FileCopyDetails 对象。我不知道 Ant 如何记录复制的文件,但一种方式可能如下:

task copyDocs(type: Copy) {
    // ...
    eachFile { details ->
        println "Copying $details.sourcePath to $details.path ..."
    }
}