In
a previous
post we learned how to run a
Java application in a Gradle project. The Java source file with a main method is part of the project and we
use the JavaExec task to run the Java code. We can use
the same JavaExec task to run a Groovy script file.
A
Groovy script file doesn't have an explicit main method, but it is added when we compile
the script file. The name of the script file is also the name of the generated
class, so we use that name for the main property of the JavaExec task. Let's first create simple Groovy
script file to display the current date. We can pass an extra argument with the
date format we wan't to use.
00.//
File: src/main/groovy/com/mrhaki/CurrentDate.groovy01.package com.mrhaki02. 03.//
If an argument is passed we assume it is the04.//
date format we want to use.05.//
Default format is dd-MM-yyyy.06.final
String dateFormat = args ? args[0]
: 'dd-MM-yyyy'07. 08.//
Output formatted current date and time.09.println "Current
date and time: ${new
Date().format(dateFormat)}"Our
Gradle build file contains the task runScript of type JavaExec.
We rely on the Groovy libraries included with Gradle, because we uselocalGroovy() as a compile dependency. Of course we
can change this to refer to another Groovy version if we want to using the
group, name and version notation together with a valid repository.
00.//
File: build.gradle01.apply
plugin: 'groovy'02. 03.dependencies
{04.compile
localGroovy()05.}06. 07.task
runScript(type: JavaExec) {08.description 'Run
Groovy script'09. 10.//
Set main property to name of Groovy script class.11.main
= 'com.mrhaki.CurrentDate'12. 13.//
Set classpath for running the Groovy script.14.classpath
= sourceSets.main.runtimeClasspath15. 16.if (project.hasProperty('custom'))
{17.//
Pass command-line argument to script.18.args
project.getProperty('custom')19.}20.}21. 22.defaultTasks 'runScript'We
can run the script with or without the project property custom and we see the changes in the
output:
$
gradle -qCurrent
date and time: 29-09-2014$
gradle -q -Pcustom=yyyyMMddCurrent
date and time: 20140929$
gradle -q -Pcustom=yyyyCurrent
date and time: 2014Code written with Gradle 2.1.