This message was deleted.
# community-support
s
This message was deleted.
a
Stranger yet, if I run
Copy code
gradle greeting -Pgreeting.message="hello3"
then I get the output
Copy code
hello2 and salutations2
What I understand is happening is that during the configuration phase, the
greeting {}
extension's properties are not yet accessible, so when
extension.getMessage().get()
is called, it returns the value set in the
convention
method Is there a way to get the value defined in the
greeting {}
extension (i.e. the value
'hello2'
) during the configuration phase?
a
The idea of Properties is, that you don’t call
get()
at configuration time, but you use for example
map()
. In your case you could do:
Copy code
Property<String> message = extension.getMessage().map(it -> {
    // if else logic here
})

project.getTasks().register("greetingTask", task -> {
    // Note: Accessing a property outside of doFirst/doLast or methods annotated with @TaskAction is actually a configuration phase
    doLast(task -> {
        // Accessing a property in doFirst/doLast is an execution phase
        System.out.println(message.get())
    });
});
If you really need to call
.get()
at configuration time you probably have to fallback to use
project.afterEvaluate()
, but that goes against the idea of Properties and “everything is lazy” principle.
a
Thank you Anze I have a followup question: If I am not supposed to access an extension Property during configuration time, what is the best practice for capturing user input to configure plugin configuration-time behavior? (assuming that accessing the user input during configuration time is a strict constraint that cannot be worked around)
a
Best practice is, that you don’t decide anything at the configuration phase. In configuration phase you only wire inputs to tasks. E.g. if user input is
-Pgreeting.message
then you make this a task input via
project.getProviders().gradleProperty("greeting.message")
. And then inside a task action you do if/else or some logic and decide what will you do with that user input. But yeah, for some special cases that might be sometimes difficult.
v
The usual pattern is, that you do not set properties then in the extension, but that the extension has functions that the user calls. So for example
Copy code
greeting {
    setMessage('hello2')
}
and then you can do the relevant things in the
setMessage
function of the the extension.
a
For the sake of comparison, the way my plugin is currently written (not the toy example above) is that it accesses properties that are set via
-Pflags
and via the
ext {}
block in the
build.gradle
file. These gradle properties are always accessible, so I can use them to decide stuff during the configuration phase
I realize this isn't the best practice, and I'm trying to migrate to using a custom extension blocks (like the
greeting{}
block above) The disadvantage is that I can no longer access these properties during configuration phase
So I can't complete the migration