Search code examples
kotlingradlegradle-kotlin-dsl

Unresolved reference: tasks.jib.doLast in build.gradle.kts


I have old Kotlin project success build by build.gradle:

tasks.jib.doLast {}

But I need to change this to build.gradle.kts:

 plugins {
  kotlin("jvm")
  id("application")
  id("com.google.cloud.tools.jib")
}

group = "com.myproject"
version = "1.0-SNAPSHOT"

application {
    mainClass.set("MainKt")
}
dependencies {
  annotationProcessor("org.springframework.boot:spring-boot-starter-data-jdbc")
  annotationProcessor("com.github.blagerweij:liquibase-sessionlock")
  annotationProcessor("org.liquibase:liquibase-core:4.8.0")
  annotationProcessor("org.postgresql:postgresql")
}

kotlin {
  jvmToolchain {
    languageVersion.set(JavaLanguageVersion.of("17"))
  }
}

jib {
  from.image = "amazoncorretto:17-alpine-jdk"
  to {
    image = "image"
    tags = setOf("$version")
  }
  container.user = "nobody"
}


tasks.jib.configure {
  dependsOn(provider {
    tasks.jibDockerBuild
  })
}

tasks.jib.doLast {
//some logic
}

and now I get error:

Line 32: doLast {
           ^ Unresolved reference: tasks.jib.doLast

Maybe shoul'd I use tasks.withType? But with this configuration it is not defined also

tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
    kotlinOptions {
        jib.doLast { }
    }
}

Thank you for all your suggestions.


Solution

  • The Groovy code

    tasks.jib.doLast {
      // someLogic
    }
    

    should be replaced in Kotlin with

    tasks.jib.configure {
      doLast {
        // someLogic
      }
    }
    

    In fact, you can include that configuration in the previous configuration block as it's doing the same thing:

    tasks.jib.configure {
      dependsOn(provider {
        tasks.jibDockerBuild
      })
      doLast {
        //some logic
      }
    }
    

    Note this difference is because in Kotlin DSL tasks.jib is a TaskProvider (via an auto-generated accessor because it was defined in a plugin) but in Groovy it's the jib Task object itself (via Groovy/Gradle magic by virtue of tasks being a NamedDomainObjectCollection.

    I encourage you to click/hover on the objects in your build script; if you are using a suitable IDE this will tell you what type they are and lead you to what API is available for them.