Gradle
uses Groovy's AntBuilder for Ant integration. But if we want to use an optional
Ant task we must do something extra, because the optional tasks and their
dependencies are not in the Gradle classpath. Luckily we only have to define our
dependencies for the optional task in the build.gradle
file
and we can define and use the optional Ant task.
In
the following sample we are using the scp Ant optional task. We define a
configuration and assign the dependencies to this configuration. Then we can
define the task and set the classpath property to the classpath of the
configuration. We use asPath
to convert the configuration classpath
for the Ant task. In the sample we also see how we can ask for user input when
the script is run. The passphrase for the ssh keyfile is a secret and we don't
want to keep it in a file somewhere, so we ask the user for it. The Java
method System.console()
return a reference to the console and
withreadPassword()
we can get the value for the
passphrase.
00.
//
File: build.gradle
01.
02.
//
We define a new configuration with the name
'sshAntTask'.
03.
//
This configuration is used to define our
dependencies.
04.
configurations
{
05.
sshAntTask
06.
}
07.
08.
//
Define the Maven central repository to look for the
dependencies.
09.
repositories
{
10.
mavenCentral()
11.
}
12.
13.
//
Assign dependencies to the sshAntTask configuration.
14.
dependencies
{
15.
sshAntTask
'org.apache.ant:ant-jsch:1.7.1'
,
'jsch:jsch:0.1.29'
16.
}
17.
18.
//
Sample task which uses the scp Ant optional task.
19.
task
update {
20.
description
=
'Update
files on remote server.'
21.
22.
//
Get passphrase from user input.
23.
def
console
= System.console()
24.
def
passphrase
= console.readPassword(
'%s:
'
,
'Please
enter the passphrase for the keyfile'
)
25.
26.
//
Redefine scp Ant task, with the classpath property set to our newly
defined
27.
//
sshAntTask configuration classpath.
28.
ant.taskdef(name:
'scp'
,
classname:
'org.apache.tools.ant.taskdefs.optional.ssh.Scp'
,
29.
classpath:
configurations.sshAntTask.asPath)
30.
31.
//
Invoke the scp Ant task. (Use gradle -i update to see the output of the Ant
task.)
32.
ant.scp(todir:
'mrhaki@servername:/home/mrhaki'
,
33.
keyfile:
'${user.home}/.ssh/id_rsa'
,
34.
passphrase:
passphrase
as
String,
//
Use phassphrase entered by the user.
35.
verbose:
'true'
)
{
36.
fileset(dir:
'work'
)
{
37.
include(name:
'**/**'
)
38.
}
39.
}
40.
}