https://kotlinlang.org logo
#gradle
Title
# gradle
s

statmark56

11/20/2023, 11:45 PM
I register a custom task in root-level build.gradle.kts:
Copy code
tasks.register<ExampleTask>("example")

abstract class ExampleTask : DefaultTask() {
    @TaskAction
    fun initialize() {
        println("Hello World")
    }
}
But when I run it
./gradlew example
I got:
Copy code
Could not create task :example
    Could not create task of type ExampleTask
        Class Build_gradle.ExampleTask is a non-static inner class.
What do I miss? Thanks
And I choose not to put it in buildSrc since it re-invalidates all modules for every single change
m

mbonnin

11/20/2023, 11:48 PM
That seems to work for me. What's your Gradle version?
e

ephemient

11/20/2023, 11:58 PM
are you sure that's all that's in your
class ExampleTask
? it must not use anything in the script context, e.g.
Copy code
val x = file(".")
abstract class ExampleTask : DefaultTask() {
    init {
        x // bad
        file(".") // also bad
☝️ 1
🎯 2
thank you color 1
s

statmark56

11/21/2023, 1:12 AM
@mbonnin I'm using 8.1 @ephemient Yes, the println is all I have inside. Weird is if I put it in buildSrc, everything is fine.
Oh you're right. My bad, I have a field which has access to
rootProject
. Removing it now works fine. But alas, I will lost all the API I need for the task logic if I choose this option (put the class task inside build script directly) :(
e

ephemient

11/21/2023, 1:23 AM
you do have access to
Task.project
inside the task class, so
project.rootProject
is OK, just
rootProject
is not. however using
project
at execution time is not allowed with configuration cache, what are you trying to do?
❤️ 1
s

statmark56

11/21/2023, 1:31 AM
so
project.rootProject
is OK,
Ah right. Thank you so much!
using
project
at execution time is not allowed with configuration cache,
Oh TIL. But if I don't have the cache enabled, all good?
what are you trying to do?
This task is to create a new File inside certain project directory. Let's just say is for improving dev productivity or so..
e

ephemient

11/21/2023, 1:35 AM
you can separate out the configuration from the execution,
Copy code
tasks.register("example", ExampleTask::class) {
    outputFile.set(rootProject.file("output.txt"))
}

abstract class ExampleTask : DefaultTask() {
    @get:OutputFile
    abstract val outputFile: RegularFileProperty

    @TaskAction
    fun initialize() {
        outputFile.get().getAsFile().writeText("Hello World")
    }
}
s

statmark56

11/21/2023, 1:37 AM
I will make a note on it 👍 Again, thanks @ephemient! *Why you always know everything in mobile landscape with such accurate analysis! 😅
v

Vampire

11/21/2023, 1:57 AM
And I choose not to put it in buildSrc since it re-invalidates all modules for every single change
Don't use
buildSrc
, but one or more included builds with one or more projects each, then only things get invalidate that actually use the changed thing. 🙂
👍 1
thank you color 1
3 Views