Skip to content

Instantly share code, notes, and snippets.

@bamboo
Created August 19, 2020 21:48
Show Gist options
  • Save bamboo/b4c9678fc44aebc623fe849351ea95d3 to your computer and use it in GitHub Desktop.
Save bamboo/b4c9678fc44aebc623fe849351ea95d3 to your computer and use it in GitHub Desktop.
BuildService + projectsEvaluated callback example
import org.gradle.tooling.events.FinishEvent
import javax.inject.Inject
abstract class TraceService : BuildService<TraceService.Parameters>, org.gradle.tooling.events.OperationCompletionListener {
private
var projectsEvaluated = false
interface Parameters : BuildServiceParameters {
}
fun onProjectsEvaluated() {
println("onProjectsEvaluated()")
projectsEvaluated = true
}
override fun onFinish(event: FinishEvent) {
if (!projectsEvaluated) {
println("from the cache!")
}
println("onFinish($event)")
}
}
open class TraceServicePlugin @Inject constructor(
private val buildEventsListenerRegistry: BuildEventsListenerRegistry
) : Plugin<Settings> {
override fun apply(target: Settings) {
target.gradle.run {
val service = sharedServices.registerIfAbsent("traceService", TraceService::class) {
parameters {
// configure service here
}
}
buildEventsListenerRegistry.onTaskCompletion(service)
projectsEvaluated {
service.get().onProjectsEvaluated()
}
}
}
}
apply<TraceServicePlugin>()
@bitspittle
Copy link

bitspittle commented Feb 14, 2022

That's a great thread, thanks for sharing. Lots of people are struggling with this :)

Luckily that approach is working for me so far. I am uncomfortable that I'm checking an interface match, since Gradle could possibly invent some different failure-ish type in the future and my code will silently stop working, which will be a pain to debug.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment