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
Related
I am calculating the value of local variable (S_STACK_ID) inside dynamic stage of jenkins pipeline
I need to pass S_STACK_ID variable to makefile so that it could be used in makefile to uniquely identify ECS Stack to be deployed
I have tried below code but it passes blank 'ARGS' to makefile
stage('build') {
steps {
script {
def stages = [failFast:true]
for (int i=1; i<5; i++) {
stages["LG ${i}"]={
stage ("LG ${i}"){
S_STACK_ID=env.STACK_ID+i
withCredentials([[
sh 'make ARGS="${S_STACK_ID}" build'
}
}
}
}
parallel stages
}
}
}
sh 'make ARGS="myStack" build' //This correclty passes "myStack" to makefile
sh 'make ARGS="${S_STACK_ID}" build' // Passess blank to makefile and not the value of S_STACK_ID which is an issue for me
Thanks
This worked as "" are required for shell commands to interpolate string literals
sh "make clean \"ARGS=${S_STACK_ID}\""
The Gradle documentation tells this:
Note that if a task has an output directory specified, any files added to that directory since the last time it was executed are ignored and will NOT cause the task to be out of date. This is so unrelated tasks may share an output directory without interfering with each other. If this is not the behaviour you want for some reason, consider using TaskOutputs.upToDateWhen(groovy.lang.Closure)
Question: How does the solution with upToDateWhen look like (so that added files are considered). The main problem is that one has to access the build cache to retrieve the output directory content hash the last time the task ran.
Not sure if I understand the question correctly or why you mention the build cache. I assume you are not aware that the predicates added with upToDateWhen() are considered in addition to any other up-to-date checks like the ones added with TaskOutputs.dir()?
Take the following sample task:
task foo {
def outDir = file('out')
outputs.dir(outDir)
outputs.upToDateWhen { outDir.listFiles().length == 1 }
doLast {
new File(outDir, 'foo.txt') << 'whatever'
}
}
As long as there is only a single file in the output directory (as configured via upToDateWhen) and the file produced by the task (out/foo.txt) isn’t changed after the task has run, the task will be up-to-date. If you change/remove the file created by the task in the output directory or if you add further files to the output directory, then the task will run again.
Updated answer as per the updated question from the comments:
task foo {
def outDir = file('out')
/* sample task action: */
doFirst {
def numOutFiles = new Random().nextInt(5)
for (int i = 1; i <= numOutFiles; i++) {
new File(outDir, "foo${i}.txt") << 'whatever'
}
}
/* up-to-date checking configuration: */
def counterFile = new File(buildDir, 'counterFile.txt')
outputs.dir(outDir)
outputs.upToDateWhen {
counterFile.isFile() \
&& counterFile.text as Integer == countFiles(outDir)
}
doLast {
counterFile.text = countFiles(outDir)
}
}
def countFiles(def dir) {
def result = 0
def files = dir.listFiles()
if (files != null) {
files.each {
result++
if (it.isDirectory()) {
result += countFiles(it)
}
}
}
result
}
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.
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.
I'm new to gradle and i tried to copy files from one folder to another using a task of "Copy" type, but it does not work. The following is my script:
def dest = 'newfolder'
task copy(type: Copy) << {
println dest
from "src"
into dest
}
But if i remove the "<<" and run gradle copy again, it works. Script like following:
def dest = 'newfolder'
task copy(type: Copy) {
println dest
from "src"
into dest
}
Why doesn't it work if i use "<<" ?
But when i run another following scripts, they all work.
task hello << {
println 'Hello world!'
}
task hello {
println 'Hello world!'
}
<< (short for doLast) adds a task action, which will be executed after the Copy task's main task action (which does the copying). At that point it's too late to configure the task, as the main action has already completed.