Provide default values for dynamic properties


(Justin Ryan) #1

In an init script before I’ve applied any plugins, I’m running into a common pattern when I want to set a variable to some default, but I want to be able to overridden via gradle.properties or via command line arguments. I end up writing something like this, e.g.

def propOverride = rootProject.hasProperty('prop') && rootProject.prop
        def prop = propOverride?:false // default value

This is because given the part of the lifecycle I’m in, if I set the property I’ll be blindly overriding what someone has already provide. If I just reference the property, e.g. rootProject.prop, it’s not guaranteed to be around. One thing Ant really has going for it is that properties are immutable, so the first one to set the variable (in a well defined order) wins. Which enables a user to specify properties via the command line and get the most expected behavior. I’d like to provide a form of a conventionMapping for these dynamic properties. Is something like this possible:

rootProject.conventionMapping.with {
    ext.prop = { 'defaultValue' }
}

I could creation a real convention for these, but I’m so early in the lifecycle that it’s not practical.


(Luke Daley) #2

For some other work we are doing, we are starting to discuss general configurability of the model from the command line. It’s almost certain that this will be geared towards overriding “defaults” so will address this issue. At the moment, the spec is at: https://github.com/gradle/gradle/blob/master/design-docs/task-configuration-from-command-line.md. It speaks about task configuration, but the discussion is leaning towards using this to work on the general problem. We’ll be talking more about this on the dev list over the coming weeks.

As for an immediate solution…

You can’t convention map an extension property. You’d simply have to create it with the default value, and then looking for the user input and assign if applicable.


(Justin Ryan) #3

Thanks for the answer.