Parse Gradle task arguments

Hi,
I have a task that needs to accept any arguments that starts with a specific prefix.
I have this :

def props = project.properties.findAll ({k,v -> k.startsWith("test_")}).collectEntries ({k,v -> [k - "test_", v]})
task name(){
doLast{
 props.each {k,v -> project.ext.setProperty(k,v)}

}
}

I want to run this in command line ;
./gradlew name -Ptest_foo=bar.

I am using the ‘test_foo’ value to override a default value in my code however it s not working as expected.It s returning the default value and does not take the command line argument into consideration.
Please any help or advice will be highly appreciated.
Note : I am pretty new to Gradle and groovy.

thank you

Hi, @taousou,

here’s my code:

def inputPropsOfArgs = project.properties
                   .findAll {it.key.startsWith("test_")}
                   .collect {[ it.key.substring("test_".length()), it.value]}

println "Got properties of prject, inputPropsOfArgs=$inputPropsOfArgs"
ext {
    ha = '1'
}
task name(){
    doFirst{ 
       println "first, ${project.ext.properties}"
       inputPropsOfArgs.each {k,v ->  
          project.ext[k] = v
          println "Put [$k , $v]"
      } 
      
    }

    doLast {
        println "=== Finally ==="
        project.ext.properties.each { k, v ->
            println k + "=" + v
        }
    }  
}

Run command

gradle -b test.gradle name -Ptest_bbb=222 -Pcc=33 -q

Result:

Got properties of prject, inputPropsOfArgs=[[bbb, 222]]
first, [cc:33, ha:1, test_bbb:222]
Put [bbb , 222]
=== Finally ===
cc=33
ha=1
bbb=222
test_bbb=222

Groovy Map Operations References

Hope it can help you, good luck!

Thanks for your answer, it works fine however wanted to set my properties in order to use them in the javacode. This is the updated code that worked for me.

    def props = project.properties
            .findAll {it.key.startsWith("test.")}
            .collect {[ it.key, it.value]}
    task name(){
    doLast{
     props.each { k, v ->
                        systemProperty k, v

    }
    }