Executing assembleRelease Gradle task does now work from custom task - android

I have the following Gradle task defined in my build.gradle file
task myTask() << {
println "Start"
assembleRelease.execute()
println "end"
}
What I want is to execute assembleRelease gradle task when I execute myTask.
However, what I get is the following output
Executing tasks: [myTask]
Configuration on demand is an incubating feature.
Relying on packaging to define the extension of the main artifact has been deprecated and is scheduled to be removed in Gradle 2.0
:gymgym:myTask
Start
end
BUILD SUCCESSFUL
As you can see, "Start" is followed by "end", meaning that assembleRelease has not been invoked.
What am I doing wrong?

Each task in Gradle is node on a DAG. It sounds like you're trying to surround one task with another, which doesn't fit the model. You can, however, append work to the beginning and/or end of any task using doFirst and doLast. If you want it to be optional, you can make it depend on an optional command line argument.
ext.SHOULD_WRAP = hasProperty('shouldWrap') ? shouldWrap.toBoolean() : false
if (SHOULD_WRAP) {
wrapAssemble()
}
def start() {
println "Start"
}
def end() {
println "end"
}
def wrapAssemble() {
assembleRelease.doFirst {
start()
}
assembleRelease.doLast {
end()
}
}
With this configuration, calling ./gradlew assembleRelease -PshouldWrap=true will execute the assemble task with your prepended and appended work. Calling ./gradlew assembleRelease -PshouldWrap=false or simple ./gradlew assembleRelease will execute the assemble task normally.
Old answer
Just set your task as a dependency for assembleRelease:
task myTask() << {
println "Start"
println "end"
}
assembleRelease.dependsOn "myTask"
Now your task will always be executed when assembleRelease is.

Related

Execute Gradle command with Gradle task

I want to re-create verification-metadata.xml file with single click. I can create verification-metadata.xml with this command ./gradlew --write-verification-metadata sha256. I try to create Gradle Task inside the build.gradle(app) and execute, but it didn't work
task verificationMeta(type: Exec) {
workingDir "${rootDir}"
commandLine './gradlew ', '--write', '-verification', '-metadata', ' sha256'
doLast {
println "Executed!"
}
}
rootDir is root directory of project.
This code gives me error;
Execution failed for task ':verificationMeta'.
> A problem occurred starting process 'command './gradlew ''
How can I make it ?
Are you working on windows machine?
We had the problem that on windows machine you have to call gradlew.bat
Example:
task prodRepackage(type: Exec) {
group = "Build"
if (OperatingSystem.current().isWindows()) {
executable "gradlew.bat"
args "-Pprod", "bootJar"
} else {
executable "./gradlew"
args "-Pprod", "bootJar"
}
}
As a workaround for the issue, I use .bat or .sh scripts to be executed as the following.
task executeCMD(type:Exec) {
workingDir '.'
commandLine 'test.bat'
doLast {
println "Executed!"
}
}
This, for example, will execute the test.bat script, which only has one line
./gradlew --write-verification-metadata sha256
if you're using Linux/macOS, you can replace the .bat with .sh.

Run a command line with Gradle and Save the output result

I want to run a command line with Gradle that this command has an output.
I run this command in windows powershell:
./mybat.bat myArgs when I hit enter, it will print some digit, like this:
123456
I want to run this command with gradle and save this result(123456)
here is some code that I written in android build.gradle file:
task getSomeOutput(type: Exec) {
workingDir "${buildDir}/output"
commandLine 'powershell', './mybat.bat' , 'foo'//this is myArgs for example
}
this works and prints the value 123456, but I want to save it in a variable, how can I do that?
As you can see in the official doc HERE
This can be achieved with the following task
task executeCMD(type:Exec) {
workingDir '.'
commandLine 'mybat.bat', '>', 'log.txt'
doLast {
println "Executed!"
}
}
This will send the output of mybat.bat execution and set the results into a txt file called log .
the . is the directory where you have the script .
in my case its a project root directory .
the best approach I found is to add '/c' to commandLine arguments and use standardOutput, here some code that might help other people:
task getSomeOutput(type: Exec) {
workingDir "${buildDir}/output"
commandLine 'powershell', '/c', './mybat.bat' , 'foo'//this is myArgs for example
standardOutput = new ByteArrayOutputStream()
doLast {
def result = standardOutput.toString()
println "the result value is: $result"
}
}

Unable to catch exception of Gradle task of type Exec

I've created a gradle task to check if a program is installed, it works fine but I discovered that it can throw an exception on environments where the command I am executing does not exist. I've tried to catch the exception that is thrown but no luck. How can I gracefully handle the exception and continue the build process if my task fails due to the command not existing?
Error:
FAILURE: Build failed with an exception.
What went wrong:
Execution failed for task ':isGitLFSInstalled'.
A problem occurred starting process 'command 'command''
Code:
task isGitLFSInstalled(type: Exec) {
commandLine 'command', '-v', 'git-lfs' // Fails here on environments that dont have "command"
ignoreExitValue true
standardOutput = new ByteArrayOutputStream()
ext.output = {
return standardOutput.toString()
}
doLast {
if (execResult.exitValue != 0) {
throw new GradleException("Git LFS is not installed, please build project after installing Git LFS.\n" +
"Refer to the following URL to setup Git LFS: https://git-lfs.github.com/")
}
}
}
The problem you're facing is described here. Surrounding commandLine with try/catch doesn't work for a simple reason: commandLine doesn't execute your command, it just sets the command to be executed by the Exec task when it will be run.
One way would be not to use tasks to execute the command. For example, you could use ProcessBuilder wrapped in try/catch in finalizedBy, which will only be run during the execution phase:
task myTask {
finalizedBy {
try {
def proc = new ProcessBuilder("command", "-v", "git-lfs")
proc.start().waitFor()
// Do something with stdout or whatever.
} catch (Exception e) {
println("Couldn't find git-lfs.")
}
}
}
I don't have much time right now, but I hope that helps.

Gradle not executing my task

I have a task that is supposed to run a shell script. In Gradle, I have defined the following:
defaultTasks 'renaming'
... some other stuff goes here ...
task renaming(type: Exec) {
commandLine 'sh', 'src/main/bin/rename.sh'
}
I have the shell script under my module in src/main/bin/
However, it is not getting run (for test purposes, the shell creates a directory called "asfasf"). How can I fix this?
As you give sh a relative path, it is resolved against the working directory of the Exec task. Either set the working directory for the Exec task or use file('src/main/bin/rename.sh') as second argument to commandLine.

Could not find method commandLine()

I'm attempting to add a pre-pre-build shell script to my gradle/Android-Studio build. I've added the following to app/build.gradle:
task prePreBuild << {
commandLine 'ls'
}
preBuild.dependsOn prePreBuild
When I invoke my build with ./gradlew assembleDebug I get the following error:
Could not find method commandLine() for arguments [ls] on project ':app'
If I replace the commandLine line with something like println 'Hello' then it works fine, and I can see the output from my new task.
I searched for other mentions of "Could not find method commandLine" and found nothing. What is the correct way to invoke a shell script from this gradle task?
You need to indicate the type of the task or use the exec block:
task execute(type: Exec) {
}
or
exec {
}
You can find more info on https://docs.gradle.org/current/dsl/org.gradle.api.tasks.Exec.html

Categories

Resources