要定义Copy
任务,我们指定我们要复制的文件以及到哪个目录。 此定义是一个CopySpec
实例。 它包含定义我们要复制内容的规则。 归档任务Jar
, Zip
和Tar
也使用CopySpec
实例。
当我们创建Copy
类型的任务时,我们将获得一个实现CopySpec
接口的任务对象。 我们可以使用该界面中的所有方法来扩展复制任务的配方。 在以下构建文件中,我们首先定义任务website
。 我们使用CopySpec
方法来配置任务。 然后,我们定义类型为Sync
的任务deploy
,该任务deploy
也实现CopySpec
接口。
// Create a new task of type Copy.
// The website task is of type Copy
// and this means it implements the
// CopySpec interface.
task website(type: Copy) {
into "${buildDir}/website"
from 'src/webroot'
into 'resources', {
from 'src/assets'
}
}
// We can use all CopySpec methods
// to add new specifications to
// the existing specifications.
website.into('resources') {
from 'src/javascript'
}
// The copySpec method creates
// a CopySpec instance
// from the closure.
// The copySpec method is part of the
// Project object.
CopySpec manualSpec = copySpec {
from('src/manual') {
include '**/*.html'
}
}
// And the with method accepts
// the CopySpec we created.
website.with(manualSpec)
// Print each file path
// that is copied.
website.eachFile {
println it.path
}
// New task of type Sync.
// The Sync task is also implementing
// the CopySpec interface.
// (Just like archive tasks: Zip, Tar, Jar)
task deploy(type: Sync) {
destinationDir = file("${buildDir}/production")
from website
}
// Use rename method from CopySpec.
deploy.rename { file ->
if (file == 'index.html') {
'main.html'
} else {
file
}
}
// And finally the exclude method.
deploy.exclude 'man.html'
当我们运行deploy
任务并查看build
目录中的文件时,我们将看到如何执行我们的复制规范:
$ gradle deploy
:website
index.html
resources/app.js
resources/site.css
man.html
:deploy
BUILD SUCCESSFUL
Total time: 3.643 secs
$ tree build/
build
├── production
│ ├── main.html
│ └── resources
│ ├── app.js
│ └── site.css
└── website
├── index.html
├── man.html
└── resources
├── app.js
└── site.css
4 directories, 7 files
翻译自: https://www.javacodegeeks.com/2014/11/gradle-goodness-using-copyspec-with-tasks.html