Hey, another CC question. I've got a task with a `...
# configuration-cache
l
Hey, another CC question. I've got a task with a
doLast { }
action. As soon as I am calling a function defined in my
build.gradle.kts
, I am getting a CC violation. I could inline the whole code of that function, but I can't believe that is the correct solution. How can I call such a function without triggering a violation? A sample would be, I just made the body as small as possible:
Copy code
tasks.register("npmInstall2") {
    doLast {
        if (changeLabel()) {
            println("changed")
        }
    }
}

fun changeLabel(): Boolean = false
Hints appreciated, thanks.
v
You cannot. Imagine the content of the script to be the body of a class. Overly simplified that is what happens. So a function in the script is a function of the script class, and "local" variables in the script are properties of the script class. So referring to either of them needs the instance of the script class which is not supported. If you have that much logic in your build script, that is not really idiomatic and you should consider moving build logic to convention plugins / custom tasks. To solve it ad-hoc, you would need to make the function not being a function of the script class. So for example have a class in that script and put the function to the companion object of that class. That way it is a static function of that class and your
doLast
can call it without a reference to the script object. Of course you need to make sure that the class and the function do not refer to anything of the script instance or the class will be non-static and thus again have a reference to the script object.
👍 1
l
Ah, sounds good. Using a
companion object { fun( .... }
does solve my immediate problem, although I have to remove the
<http://logger.info|logger.info>()
calls which would bring back the reference to the script object - do you have an idea how to log stuff via gradle in such a function defined in a companion class?
v
Copy code
Logging.getLogger("foo").info("foo")
l
Thx again, works like a charm.
👌 1
r
Capturing the logger reference as a local variable in the configuration action should work as well. Or using
Task.getLogger()
(if the output should be associated with a task)
👍 1
v
Which is hard to do in a function that is not in the task. 😄
Well, you could of course give the logger as argument to the function
l
I considered using it as an argument to get the task logger, but finally settled on using Logging.getLogger(..) - sufficient for my usecase.
👌 1