Search code examples
kotlingradleshadowjar

How to configure Shadow plugin using kotlin dsl


I can't figure out how to use the shadow plugin inside a gradle build with kotlin DSL. All the documentation is using the groovy dsl.

This is the content of build.gradle.kts:

import groovy.lang.GroovyObject
import org.gradle.jvm.tasks.Jar

plugins {
    // Apply the Kotlin JVM plugin to add support for Kotlin.
    id("org.jetbrains.kotlin.jvm") version "1.4.10"

    id("com.github.johnrengelman.shadow") version "6.1.0"
    application
}

allprojects {
    repositories {
        // Use jcenter for resolving dependencies.
        // You can declare any Maven/Ivy/file repository here.
        jcenter()
    }
    group = "com.example"
    version = "1.0-SNAPSHOT"
}

dependencies {
    // Align versions of all Kotlin components
    implementation(platform("org.jetbrains.kotlin:kotlin-bom"))

    // Use the Kotlin JDK 8 standard library.
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
}

application {
    mainClass.set("com.example.MainKt")
}


tasks.withType<Jar> {
    manifest {
        attributes(
                mapOf(
                    "ImplementationTitle" to project.name,
                    "Implementation-Version" to project.version)
        )
    }
}

And this is the content for src/main/kotlin/com/example/Main.kt

package com.example

fun main() {
    println("Hello world")
}

But when I try to do gradle build, I get this error:

A problem was found with the configuration of task ':shadowJar' (type 'ShadowJar').
> No value has been specified for property 'mainClassName'.

which I think is weird, since I've already entered the application main class inside the application argument.

I've tried to add this:

tasks.withType<ShadowJar>() {
    mainClassName = "com.example.MainKt"
}

But when I try to build with this option, it complains that it can't find the ShadowJar type.

  Line 22: tasks.withType<ShadowJar>() {
                          ^ Unresolved reference: ShadowJar

What am I doing wrong here?


Solution

  • The problem was that I tried to add mainClassName to the ShadowJar task, it should have been added to the application function. Like this:

    application {
        val name = "com.cognite.ingestionservice.MainKt"
        mainClass.set(name)
    
        // Required by ShadowJar.
        mainClassName = name
    }
    

    The mainClassName property is deprecated, but is still required by ShadowJar as of version 6.1.0.

    mainClass.set() is not necessary when adding mainClassName, but it was in the documentation for gradle 6.7, so I added it anyway.