Gradle
scripts are Groovy scripts. So we can use all the functionality of Groovy in our
Gradle scripts. And because we can use Java classes as well, we can simply get
user input values from the console using java.io.Console.
With the Console class we can for example ask for a
value to be used in our script. We can even ask for a password without the
password being echoed on the console.
In
the following sample build script we have a ask task that uses Console to let the user enter a username and
password value. In the print task we use the values that are entered
to print them to the console.
00.def username01.def password02. 03.task
ask << {04.def console
= System.console()05.if (console)
{06.username
= console.readLine('>
Please enter your username: ')07.password
= console.readPassword('>
Please enter your password: ')08.} else {09.logger.error "Cannot
get console."10.}11.}12. 13.task print <<
{14.println "Hello
$username! Your password is ${password.size()}
characters."15.}We can run the script (suppose we use help as password):
0.$
gradle -q ask print1.>
Please enter your username: mrhaki2.>
Please enter your password:3.Hello
mrhaki! Your password is 4
characters.