How do you use Proguard with Kotlin? (Not Android)

As title, there are many examples about using Proguard with Android. However, there is nearly no example for a Kotlin Gradle project. When I trying to include Proguard, it creates many unresolved references.

Here is my build.gradle:

import proguard.gradle.ProGuardTask

group "com.example"
version "1.0.0"

buildscript {
    ext.kotlin_version = "1.1.3-2"

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "net.sf.proguard:proguard-gradle:5.3.3"
    }
}

apply plugin: "kotlin"

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
    testCompile "org.mockito:mockito-core:2.8.47"
    testCompile "junit:junit:4.12"
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

jar {
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
}

task proguard(type: ProGuardTask, dependsOn: "jar") {
    injars jar.archivePath
    injars configurations.compile
    outjars "proguard.jar"
    keep 'public class com.example { *; }'
}
1 Like

I used code from their site:

tasks.register<ProGuardTask>("proguard") {
    configuration("proguard-rules.pro")

    injars(tasks.named<Jar>("jar").flatMap { it.archiveFile })

    // Automatically handle the Java version of this build.
    if (System.getProperty("java.version").startsWith("1.")) {
        // Before Java 9, the runtime classes were packaged in a single jar file.
        libraryjars("${System.getProperty("java.home")}/lib/rt.jar")
    } else {
        // As of Java 9, the runtime classes are packaged in modular jmod files.
        libraryjars(
            mapOf("jarfilter" to "!**.jar", "filter" to "!module-info.class"),
            "${System.getProperty("java.home")}/jmods/java.base.jmod"
        )
        //libraryjars "${System.getProperty('java.home')}/jmods/....."
    }

    verbose()

    val baseCoordinates = "my-kserver" // Provide the appropriate value for baseCoordinates
    outjars(layout.buildDirectory.file("libs/${baseCoordinates}-minified.jar"))
}

But it doesn’t work for me: I have warnings that every class is missed. Also not sure what baseCoordinates is.

I didn’t use ProGuard for years, but you need to specify entry points to your application. Otherwise, ProGuard assumes all your code base is unused and removes it.

baseCoordinates doesn’t seem important - it is only used to name the resulting file.

What if you need to publish your .jar in public (for Github Actions CI/CD or other purposes)?