Get user choice before execution of Gradle task - gradle

I am switching our application for Capistrano deployment to Gradle .
Here requirement to make the script user interactive .
I am stuck to provide the user input in between task .
task('hello') << {
println "hello" }
task('copy', type: Copy) {
some_user_input = prompt("Are you sure to copy this file. ") ... // Here wants something like that
if(some_user_input==true){
from(file('srcDir'))
into(buildDir)
} }
I am searching for the solution of such issue . If you know about such way than please let me know .
Thanks in advance .

Gradle lets you use existing Ant tasks within your build script. You could use the [Ant input task][1] to achieve this:
ant.input(message: 'Are you sure to copy this file?', validargs: 'y,n', addproperty: 'doDeleteFile')
if(ant.doDeleteFile == 'y') {
// Call copy task
}
Note that unlike System.console() this also works with the Gradle Daemon (tested on Linux).

Have you tried using the console? Something like this:
if (System.console().readLine().toLowerCase() == 'y') ...

Related

how to play audio in gradle.kts? [duplicate]

I have a gradle build setup at the beginning of which I want to execute a shellscript in a subdirectory that prepares my environment.
task build << {
}
task preBuild << {
println 'do prebuild stuff:'
}
task myPrebuildTask(type: Exec) {
workingDir "$projectDir/mySubDir"
commandLine './myScript.sh'
}
build.dependsOn preBuild
preBuild.dependsOn myPrebuildTask
However, when I execute the task either by calling gradle myPrebuildTask or by simply building the project, the following error occurs:
> A problem occurred starting process 'command './myScript.sh''
Unfortunately, thats all I get.
I have also tried the following - same error.
commandLine 'sh mySubDir/myScript.sh'
I use Gradle 1.10 (needed by Android) on Windows, inside a Cygwin shell. Any ideas?
use
commandLine 'sh', './myScript.sh'
your script itself is not a program itself, that's why you have to declare 'sh' as the program and the path to your script as an argument.
A more generic way of writing the exec task, but portable for Windows/Linux, if you are invoking a command file on the PATH:
task myPrebuildTask(type: Exec) {
workingDir "$projectDir/mySubDir"
if (System.getProperty('os.name').toLowerCase(Locale.ROOT).contains('windows')) {
commandLine 'cmd', '/c', 'mycommand'
} else {
commandLine 'sh', '-c', 'mycommand'
}
}
This doesn't directly address the use case for the OP (since there is script file in the working directory), but the title of the question is more generic (and drew me here), so it could help someone maybe.
unfortunately options with commandLine not worked for me in any way and my friend find other way with executable
executable "./myScript.sh"
and full task would be
task startScript() {
doLast {
exec {
executable "./myScript.sh"
}
}
}
This works for me in my Android project
preBuild.doFirst {
println("Executing myScript")
def proc = "mySubDir/myScript.sh".execute()
proc.waitForProcessOutput(System.out, System.err)
}
See here for explanation:
How to make System command calls in Java/Groovy?
This is a solution for Kotlin DSL (build.gradle.kts) derived from Charlie Lee's answer:
task<Exec>("MyTask") {
doLast {
commandLine("git")
.args("rev-parse", "--verify", "--short", "HEAD")
.workingDir(rootProject.projectDir)
}
}
Another approach using the Java standard ProcessBuilder API:
tasks.create("MyTask") {
val command = "git rev-parse --verify --short HEAD"
doLast {
val process = ProcessBuilder()
.command(command.split(" "))
.directory(rootProject.projectDir)
.redirectOutput(Redirect.INHERIT)
.redirectError(Redirect.INHERIT)
.start()
process.waitFor(60, TimeUnit.SECONDS)
val result = process.inputStream.bufferedReader().readText()
println(result)
}
}
For more information see:
How to run a command line command with Kotlin DSL in Gradle 6.1.1?
How to invoke external command from within Kotlin code?
for kotlin gradle you can use
Runtime.getRuntime().exec("./my_script.sh")
I copied my shell scipt to /usr/local/bin with +x permission and used it as just another command:
commandLine 'my_script.sh'

If else in Gradle scripts

I have this really strange behavior in Gradle and I cannot find a way out of it. In my gradle.properties file, I am using this checking condition:
//gradle.properties
if ( "${System.Property['DATABASE_DIR']}".compareTo('swdb') == 0 ) {
PROJECT_DATABASE_PATH=../database/swdb/include
}
else {
PROJECT_DATABASE_PATH=../database/include/
}
I created a new task called printProperties and it looks like this.
//build.gradle
task printProperties {
println "${System.properties['DATABASE_DIR']}".compareTo('swdb') == 0
println PROJECT_DATABASE_PATH
}
I get the following output when I run the printProperties task.
$gradle printProperties -DDATABASE_DIR=swdb
true
../database/include/
:printProperties UP-TO-DATE
BUILD SUCCESSFUL
Total time: 1.07 secs
It is really strange that the task prints true but the gradle.properties file does not evaluate the same condition correctly. Could anybody help me with this?
Your code shall take place in a init.gradle script.
You can find documentation here : https://docs.gradle.org/current/userguide/init_scripts.html
gradle.properties file is only for key=value pairs

gradle custom properties and println

I'm very new to gradle so I'm trying to make sense of it. I'm trying to print the custom properties using println and it works when I just use the property. But as soon as I put it in a string it fails and I'm not sure what is going on.
gradle.properties looks like this:
version = '2.0'
description = 'Project Description'
project.ext {
winADTSDKManager = 'SDK Manager.exe'
winADTSDKManagerPath = 'C:/Projects/WinSDKEnv/sdk/adt'
}
in build.gradle I try to run the code:
task androidSDKManager << {
description = 'Run Android SDK Manager'
println project.ext.winADTSDKManagerPath
println 'Starting: $project.ext.winADTSDKManagerPath'
}
The output looks like this:
c:\Projects\Prototypes\STouchGradle>gradle androidSDKManager
:androidSDKManager
'C:/Projects/WinSDKEnv/sdk/adt'
Starting: $project.ext.winADTSDKManagerPath
The second println statement is not printing the path like the one above. Any ideas on what is wrong with what im doing?
Update: 7/27/2014
OK I figured it out. I need to use double quotes like this
println "Starting: $project.ext.winADTSDKManagerPath"

Gradle fails with error execCommand == null

I have searched for a while for this problem and am not able to solve it. I pulled a project down from a private git repo. Some people are able to build while others like myself are getting the following error:
Error:Gradle:Execution failed for task ':ProjectName:buildNative'.
> execCommand == null!
If anybody has encountered this and knows how to fix it, please let me know, it does not seem like a problem which is specific to the project I am on.
I think this is the part in the Gradle file where it is failing:
task buildNative(type: Exec) {
if (System.env.ANDROID_NDK_HOME != null) {
def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build')
commandLine ndkBuild
} else {
doLast {
println '##################'
println 'Skipping NDK build'
println 'Reason: ANDROID_NDK_HOME not set.'
println '##################'
}
}
}
Seems like you don't have an ANDROID_NDK_HOME environment variable set. The code above doesn't treat that case correctly. As such, the problem is specific to your build. One way to fix it is to replace doLast with doFirst and to insert throw new StopExecutionException() after the printlns. Additionally you may have to set commandLine (or executable) to a dummy value.

Gradle executes all tasks?

I have a very simple build script like so
task hello{
println("hello World")
}
task bye {
println("bye")
}
On the command line I run
gradle hello and I get the following output:
hello World
bye
:hello UP-TO-DATE
Why is it executing the task "bye" (I'm assuming it gets executed since "bye" gets printed)? Thanks.
It's a common pitfall:
task hello {
println("Any code in here is about *configuring* the\
task. By default, all tasks always get configured.")
doLast {
println("Any code in here is about *executing* the task.\
This code only gets run if and when Gradle decides to execute the task.")
}
}
The distinction between configuration phase and execution phase is probably the single most important concept to understand in Gradle. It can be confusing at first, and may go away in the future. A kind of analogue in the Ant/Maven world is that these tools first parse XML build scripts and build an object model (perhaps resolving some properties along the way), and only then execute the build.
Adding to Peter answer, If you want to execute all task , you can specify the defaultTasks list.
defaultTasks 'clean', 'run'
task clean {
doLast {
println 'Default Cleaning!'
}
}
task run {
doLast {
println 'Default Running!'
}
}
task other {
doLast {
println "I'm not a default task!"
}
}
Output
Output of gradle -q
> gradle -q
Default Cleaning!
Default Running!
More details can be found here
https://docs.gradle.org/current/userguide/tutorial_using_tasks.html

Resources