If I change my ~/.gradle/init.gradle
to the following:
def hi() {
println "hello"
}
hi()
initscript {
}
Then running a gradle build outputs:
hello
> Task :prepareKotlinBuildScriptModel UP-TO-DATE
BUILD SUCCESSFUL in 366ms
But if I change ~/.gradle/init.gradle
to this:
def hi() {
println "hello"
}
initscript {
hi()
}
Then the gradle build outputs:
FAILURE: Build failed with an exception.
* Where:
Initialization script '~/.gradle/init.gradle' line: 6
* What went wrong:
A problem occurred evaluating initialization script.
> Could not find method hi() for arguments [] on object of type org.gradle.api.internal.initialization.DefaultScriptHandler.
Why is this?
And how can I invoke hi()
from within the initscript block?
CodePudding user response:
see link below to understand the initscript
closure better - in short you can not do actions inside; you can only configure - see diff example of linking actions to tasks https://docs.gradle.org/current/userguide/init_scripts.html#sec:writing_an_init_script
CodePudding user response:
Credit to ephemient from the Gradle community-support slack channel:
buildscript
,initscript
,plugins
, andpluginManagement
are all special blocks that extracted and run separately, before any other part of the script. this is necessary because Gradle needs to use them to set up the build environment for the rest of the script. you cannot use anything defined outside of the block, in these blocks.
Another note: if I change init.gradle
to
initscript {
def hi() {
println "hello"
}
hi()
}
then the following error is output:
FAILURE: Build failed with an exception.
* Where:
Initialization script '~/.gradle/init.gradle' line: 2
* What went wrong:
Could not compile initialization script '/Users/aloneitan/.gradle/init.gradle'.
> startup failed:
initialization script '~/.gradle/init.gradle': 2: Method definition not expected here. Please define the method at an appropriate place or perhaps try using a block/Closure instead. at line: 2 column: 5. File: _BuildScript_ @ line 2, column 5.
def hi() {
^
1 error
It appears that the answer is that it is not possible to define a method to be used inside initscript
using Groovy
It is worth noting that it is possible in Kotlin, though.