Gradle task while init db - gradle

task initdb() {
doLast {// Make sure the code is run during execution phase and not configuration phase
def dbUrl = 'jdbc:oracle:thin:#//172.31.0.50:1521/FCJ12PROD'
def dbUsername = 'iba_app'
def dbPassword = 'iba_app'
def dbDriver = 'oracle.driver.jdbc.OracleDriver'
def sql = groovy.sql.Sql.newInstance(dbUrl, dbUsername, dbPassword, dbDriver)
}
}
Daemon will be stopped at the end of the build stopping after processing
Task :initdb FAILED
FAILURE: Build failed with an exception.
Where:
Build file 'C:\CodesIBAR\chasis\build.gradle' line: 220
What went wrong:
Execution failed for task ':initdb'.
Could not set unknown property 'dbDriver' for task ':initdb' of type org.gradle.api.DefaultTask.
Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Related

Gradle Task - unable to execute fibonacci series in groovy

Facing problem in a question:
Write a gradle program to generate 10 fibonaci series, with task name as fibo, and variable name as num. Use command line argument for num.
For example, if a task name is test and I want to pass 10 as the input, use gradle test -Pnum=10.
I have created a function:
def fibo(n){
a = 0
b = 1
if (n == 1)
println a
else if
(n == 2)
println a + " " + b
else if (n > 2) {
print a + " " + b
i = 2
while (i <= n)
{
c = a + b
print " " + c
a = b
b = c
i = i + 1
}
}
}
My question is, how to link it with a task as I encounter error like:
FAILURE: Build failed with an exception.
* What went wrong:
Task 'fibo' not found in root project 'root'.
* Try:
Run gradle tasks to get a list of available tasks. Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
Total time: 2.61 secs
or how to pass parameters in a gradle task?
Note: Please do not suggest optimization in fibonacci code, thats not a concern for now.
You can define a task like this:
def hello(name) {
println "Hello, $name"
}
task sayHello() {
doLast {
hello sayHelloTo
}
}
And call it like this:
% gradle sayHello -PsayHelloTo=World
> Task :sayHello
Hello, World
BUILD SUCCESSFUL in 518ms
1 actionable task: 1 executed
def fibo(num) {
if (num < 2) {
return 1
} else {
return fibo(num-2) + fib(num-1)
}
}
task (fibo) << {
println fibo(5)
}

how to archive artifacts at the end of pipeline stage

I have the following pipeline
node ("testNode"){
dev env = ${ENV};
stage ("Copy artifact"){
copyArtifacts(projectName: 'appBuildJob',selector: lastCompleted());
}
stage ("Archive artifact"){
// Archive the build output artifacts.
archiveArtifacts artifacts: 'app/build/outputs/apk/app-${ENV}.apk';
}
stage ('env1'){
if (env == "env1") {
buildResult = build(job: 'env1Tests',propagate: false).result;
currentBuild.description = 'env1 - ' + buildResult
} else {
echo 'Env param is ' + env +'. Nothing to do here.';
}
}
stage ('env2'){
if (env == "env2") {
buildResult = build(job: 'env2Tests',propagate: false).result;
currentBuild.description = 'env2 - ' + buildResult
} else {
echo 'Env param is ' + env +'. Nothing to do here.';
}
}
}
My problem is that the job appBuildJob can have either env1 or env2 param and both env1Tests and env2Tests depends on the artifact of my pipeline. So if for example now runs env1 it saves the artifact and everything. Then if I run env2 my env2Tests will fail because it can't find env2 app, it will find only env1 app. After this fails and the pipeline ends i have my env2 artifact saved. So if I run immediately emv2 it will work
I want to save and overwrite the artifact at the end of the "Archive artifact" stage but it only does that when all the pipeline ended.

execute bash command in a gradle function

I want to create a generic function in gradle that executes a command. This function is called from a task.
The function executeCommand is triggered from the task copyFile but it seems that the commandLine commands are not executed. I did this because I need a generic ececuteCommand functionality that is triggered from multiple jobs.
def executeCommand(execCmd) {
try {
exec {
println("execute $execCmd in .")
commandLine 'bash', '-c', "ls -la"
commandLine 'bash', '-c', "${execCmd}"
}
}
catch(Exception e){
println("Exception: $e")
}
}
task copyFile {
doLast {
if(project.hasProperty('file')) {
ext.myFile = file
def execCmd="cp ${myFile} ."
executeCommand(${execCmd})
}
else {
println("Please specifiy argument files -Pfile=SRC_PATH")
}
}
}
There is a syntax error in your script, you should normally have an error as follows during execution:
* What went wrong:
Execution failed for task ':copyFile'.
> Could not find method $() for arguments [build_djiuilz6w3giaud8hgmf0oze7$_run_closure2$_closure5$_closure6#57fdda61] on task ':copyFile' of type org.gradle.api.DefaultTask. (normally you should have an error when trying to execute it : **
you need to replace the following statement in your copyFile.doLast{ } block:
executeCommand(${execCmd})
with:
executeCommand( execCmd)
// or: executeCommand( "${execCmd}" )
NOTE: in the exec {} block of your executeCommand function, there are two calls to commandLine function: only the second one will have effect so the command 'ls -al' will never be executed.
The rest of your script seems valid and should work as expected.

Call one Gradle Task from another with arguments

I have a gradle task which calls a script and passed the command line arguments to the script using -PARGS.
task taskAll(type: Exec, dependsOn: taskinit) {
environment['PROJECT_ROOT'] = "${projectDir}"
workingDir rootProject.projectDir.path
description = 'Main task'
executable rootProject.projectDir.path + "/execute.me"
if (project.hasProperty('ARGS')) {
args(ARGS.split(','))
}
}
I call this gradle task with any of the below options
./gradlew taskAll
./gradlew taskAll -PARGS="arg1"
./gradlew taskAll -PARGS="arg2"
However, am looking to see if I split taskAll into multiple tasks, say
./gradlew taskA #Calls task taskAll with arg1
./gradlew taskB #Calls task taskAll with arg2
I understand that I will have to replicate the taskAll to create taskA, taskB and remove the "if" condition and hardcode args in each of these.
However, I wonder if it is possible to have a cleaner implementation by having MainTask which only calls the executable, and then have TaskA, TaskB, TaskC call MainTask and pass the arguments arg1, arg2 and arg3.
In most cases, executing one task from another is done by configuration of task dependencies, via providing dependsOn and optionally mustRunAfter properies. In your case, it's not possible to use it, since your main task has to be executed after some configuration task. In that case, you can use finalizedBy property of the task.
For your requirements, you can create a number of tasks, which will set some script variable with predefined arguments, just as you need it. And you could leave your main task, which will call something, relying on this arguments. Only thing you need to do, is to make each custom task finilizedBy your main task. So, every call of custom task will execute the main task after excution.
Here is the short example, how to do it:
//define a variable to store arguments
def ARGS = null
//2 custom tasks, which set arguments during the execution phase
task taskA << {
ARGS = "poperty1,property2"
}
task taskB << {
ARGS = "property3,property4"
}
//your main task
task mainTask (type: Exec) {
environment['PROJECT_ROOT'] = "${projectDir}"
workingDir rootProject.projectDir.path
description = 'Main task'
executable rootProject.projectDir.path + "/execute.me"
//here is the main difference, we moved arguments setting into
//execution phase, before execution of this task
doFirst{
//if you call custom task it will be executed with predefined params
if (ARGS != null) {
args(ARGS)
//if you call mainTask, you are able to pass arguments via command line with -PCOMMAND_LINE_ARGS=123
} else if (project.hasProperty('COMMAND_LINE_ARGS')) {
args(COMMAND_LINE_ARGS)
} else {
throw new GradleException("No arguments found")
}
}
}
//finilization settings for custom tasks
taskA.finalizedBy mainTask
taskB.finalizedBy mainTask
A prettier way to do that with GradleBuild API:
task ('taskA', type: GradleBuild) {
startParameter.projectProperties = ['ARGS':'arg1']
tasks = ['taskAll']
}
task ('taskB', type: GradleBuild) {
startParameter.projectProperties = ['ARGS':'arg2']
tasks = ['taskAll']
}
You can have complex project properties, for example command line argument -Pmyextension.config=true will become :
startParameter.projectProperties = ['myextension.config':true]
Note that this will erase CLI args. If you need to append it :
startParameter.projectProperties << project.getGradle().getStartParameter().getProjectProperties() << ['myextension.config':true]
You can use ext:
task outraTask << {
printf(arg0)
printf(arg1)
}
project(':projetc2').tasks.outraTask {
ext.arg0 = "0"
ext.arg1 = "1"
}.execute()
output:
> Task :projetc2:outraTask
0
1

Gradle - StopExecutionException doesn't change TaskStatus

I have three gradle Tasks: A, B and B2. They depend on each other in the following way: A <- B <- B2 (meaning B depends on A and B2 depends on B). Here is my code:
task A {
println "Exec A"
}
task B(dependsOn: A) << {
throw new StopExecutionException("skip this task") // this exception prevents the println, but doesn't change the TaskStatus of B
println "Exec B"
}
task B2(dependsOn: B) << {
println "Did work: " + B.getState().getDidWork();
println "Exec: " + B.getState().getExecuted();
println "Failure: " + B.getState().getFailure();
println "Skip message: " + B.getState().getSkipMessage();
println "Skipped: " + B.getState().getSkipped();
println "Exec B2"
}
When I execute this (by running gralde -q B2), I get the following output:
> gralde -q B2
Exec A
Did work: true
Exec: true
Failure: null
Skip message: null
Skipped: false
Exec B2
As can be seen, the properties of the TaskState didn't change although the StopExecutionException was thrown correctly. How can I determine in a task if all former tasks were executed completely?
StopExecutionException is simply a shortcut to finish the task execution. The task doesn't fail if it is thrown as you can read in documentation neither is the task skipped. You can throw GradleException to make the task fail and then the subsequent task will be able to check the result. Note that you will need to change B2 to make it a finalizing task of B (see here) or play with runAfter or something similar.

Resources