Optional Ant task dependencies
We can reuse the existing Ant tasks in Gradle. The default tasks from Ant can be invoked from within our build scripts. However, if we want to use an optional Ant task, we must define a dependency for the classes needed by the optional Ant task. We create a new dependency configuration, and then we add a dependency to this new configuration. We can reference this configuration when setting the classpath for the optional Ant task.
Let's add the optional Ant task SCP for the secure copying of files to/from a remote server. We create the sshAntTask
configuration to add dependencies for the optional Ant task. We can choose any name for the configuration. To define the optional task, we use the taskdef
method from the internal ant
object. The method takes a classpath
attribute, which must be the actual path of all files of the sshAntTask
dependencies. The Configuration
class provides the asPath
property to return the path to the files in a platform-specific way. So, if we use this on a Windows computer, the file path separator is a ;
and for other platforms it is a :
. The following example build file contains all the code to define and uses the SCP Ant task:
configurations { // We define a new dependency configuration. // This configuration is used to assign // dependencies to, that are needed by the // optional Ant task scp. sshAntTask } repositories { // Repository definition to download dependencies. jcenter() } dependencies { // Define external module dependencies // for the scp Ant task. sshAntTask(group: 'org.apache.ant', name: 'ant-jsch', version: '1.9.4') } // New task that used Ant scp task. task copyRemote( description: 'Secure copy files to remote server') << { // Define optional Ant task scp. ant.taskdef( name: 'scp', classname: 'org.apache.tools.ant.taskdefs.optional.ssh.Scp', // Set classpath based on dependencies assigned // to sshAntTask configuration. The asPath property // returns a platform-specific string value // with the dependency JAR files. classpath: configurations.sshAntTask.asPath) // Invoke scp task we just defined. ant.scp( todir: 'user@server:/home/user/upload', keyFile: '${user.home}/.ssh/id_rsa', passphrase: '***', verbose: true) { fileset(dir: 'html/files') { include name: '**/**' } } }