Basem_V
Basem_V

Reputation: 61

How to use a parameter in gradle copy task in the destination folder?

Given the following task in gradle, the dev would start a new module by:

gradle initModule -PmoduleName=derp

task initModule(type: Copy) {
    description "Initialize an empty module based on the template. Usage: gradle initModule -P moduleName=derp"

    onlyIf { project.hasProperty("moduleName") }

    from "$rootDir/modules/template"
    into "$rootDir/modules/$moduleName"
}    

I am unable to run gradle since moduleName is not defined during evaluation, although I was hoping that "onlyIf" would do so.

To solve this I assign it to a locally defined variable in a guard block:

def modName = ""

if (!project.hasProperty("moduleName")) {
    logger.error("Invalid moduleName : It can't be")
} else {
    modName = moduleName
}

and finally use the new variable to survive the configuration phase.

Is this the right way to do this? It just doesn't feel right.

Additionally if I was using a rule to make this a tad more elegant:

tasks.addRule("Pattern: initModule_<mod name>") { String taskName ->

    if (taskName.startsWith("initModule_")) {
        def params = taskName.split('_');
        task(taskName)  {    
            doLast {
                project.ext.moduleName = params.tail().head()
                tasks.initModule.execute()
            }    
        }
    }
}

The moduleName is not passed around (even if I change it to finalizedBy).

Any help is appreciated.

Upvotes: 4

Views: 2275

Answers (1)

Peter
Peter

Reputation: 793

As you already figured out the property is not available during the configuration phase.

But can postpone the look-up to the execution phase by using

into "$rootDir/modules/" + project.property("moduleName")

instead of

into "$rootDir/modules/$moduleName"

Upvotes: 1

Related Questions