Search code examples
gradlegradlew

Can you run a task multiple times with different system parameters in gradle?


So I have a project where I want to run a task multiple times with a different value for a system parameter each time, however I can't seem to do that short of calling gradle multiple times in a bash script which is not desirable. I tried ./gradlew myTask -Dproperty="value1" myTask -Dproperty="value2" which ran myTask twice, which was good, but it ran with property=value2 both times. Is there any way to do this?

Edit: I should also mention that I do not know value1 and value2 until buildtime. So I can't hardcore them into the build script.


Solution

  • Check out the following approach:

    task executeTaskTwiceWithParameters {
        String[] propertyValues = System.getProperty("propertyValues" ,"").split(",")
        dependsOn propertyValues.collect { "runWith$it" }
        propertyValues.each { value ->
            task "runWith$value"(type: GradleBuild) {
                buildFile = 'build.gradle'
                tasks = ['doSomething']
                startParameter.systemPropertiesArgs += [property: value]
            }
        }
    }
    
    task doSomething {
        doLast {
            println System.getProperty("property")
        }
    }
    

    When invoked like

    ./gradlew executeTaskTwiceWithParameters -DpropertyValues=value1,value2
    

    for each property value it launches an auxiliary gradle build to execute a task with this property value set. The same trick works for project properties as well.