Cannot generate a KMP library correctly and use it in a KMM library project - kotlin

I am currently working on a project that implements the following steps:
generation of a KMP project for an API using open api generator and a swagger description file
package the common, jvm and iOS libraries
create a KMM project
add the libraries generated during the step 2 and use it
The step number 1 works correctly.
For the step number 2, I use the assemble gradle task. This task generates the following binaries in the build/libs folder:
kotlin-client-iosarm64-1.0.0-metadata.jar
kotlin-client-iosx64-1.0.0-metadata.jar
kotlin-client-js-1.0.0.jar
kotlin-client-jvm-1.0.0.jar
kotlin-client-metadata-1.0.0.jar
For the step 3, I use Android Studio and the "Kotlin Multiplatform Mobile" plugin from JetBrains and I select the "Kotlin Multiplatform Library" template.
Currently, I do not deploy the generated binaries on a maven repository. So for the step number 4, I copy/past the jar files into a "libs" folder and I reference them into the build.gradle.kts file:
sourceSets {
val commonMain by getting {
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:1.3.3")
implementation("io.ktor:ktor-client-core:2.1.3")
implementation("io.ktor:ktor-client-serialization:2.1.3")
implementation("io.ktor:ktor-client-content-negotiation:2.1.3")
implementation("io.ktor:ktor-serialization-kotlinx-json:2.1.3")
implementation(files("libs/kotlin-client-metadata-1.0.0.jar"))
}
}
val commonTest by getting {
dependencies {
implementation(kotlin("test"))
}
}
val androidMain by getting {
dependencies {
implementation("io.ktor:ktor-client-cio-jvm:2.1.3")
implementation(files("libs/kotlin-client-jvm-1.0.0.jar"))
}
}
val androidUnitTest by getting
val iosX64Main by getting {
dependencies {
implementation("io.ktor:ktor-client-ios:2.1.3")
implementation(files("libs/kotlin-client-iosx64-1.0.0-metadata.jar"))
}
}
val iosArm64Main by getting {
dependencies {
implementation("io.ktor:ktor-client-ios:2.1.3")
implementation(files("libs/kotlin-client-iosarm64-1.0.0-metadata.jar"))
}
}
val iosSimulatorArm64Main by getting
val iosMain by creating {
dependsOn(commonMain)
iosX64Main.dependsOn(this)
iosArm64Main.dependsOn(this)
iosSimulatorArm64Main.dependsOn(this)
}
val iosX64Test by getting
val iosArm64Test by getting
val iosSimulatorArm64Test by getting
val iosTest by creating {
dependsOn(commonTest)
iosX64Test.dependsOn(this)
iosArm64Test.dependsOn(this)
iosSimulatorArm64Test.dependsOn(this)
}
}
Using this configuration, it seems to work only for the android part of my KMM library project.
In fact, in my KMM library project, I can use classes from my KMP project into classes of the "androidMain" folder. But when I am trying to use the same classes into classes of the "commonMain" or the "iosMain" folders, it does not work. Classes cannot be find (Unresolved reference).
What is wrong with my project? How can I package my KMP library in order to use it in a KMM library?

The main reason that you can't use your library in iOS and common code, because files kotlin-client-*-metadata.jar are just metadata. For multiplatform and native code Kotlin use special format of libraries *.klib. Please take a look at article that explains this.
If you don't want to publish your library and want to use local setup, no need to build the library, this is not a Gradle way. Place your library near your main code and take advantage of multi project builds and add dependency to your lib project:
val commonMain by getting {
dependencies {
//...
implementation(project(":kotlin-client"))
}
}
// no need to add to another source sets, if your library already supports all targets
Or publish it in local Maven repository.

Related

Kotest + Multiplatform Kotlin/JS project: Unable to initialize main class io.kotest.launcher.LauncherKt

Having troubles setting up Kotest in my multiplatform project (only using JS, multiplatform part is needed for some libraries).
Here's relevant parts of my Gradle file. If this is relevant, it's in one of the modules of a project, I have multiple projects that create a separate html and js files, and then collect them in one place with a separate task (using template from Kromex to write a browser extension)
js(IR) {
binaries.executable()
useCommonJs()
browser {
webpackTask {
outputFileName = "base.js"
sourceMaps = false
report = true
}
distribution {
directory = File("$projectDir/../build/distributions/")
}
}
}
sourceSets {
val jsMain by getting {
dependencies {
...
}
}
val jsTest by getting {
dependencies {
implementation("io.kotest:kotest-framework-engine:5.5.1")
implementation("io.kotest:kotest-assertions-core:5.5.1")
implementation("io.kotest:kotest-property:5.5.1")
}
}
}
I tried both this, and also with kotest-framework-engine in commonTest (as specified in quickstart guide) - result is the same.
At first, after trying to run it (with Intellij Plugin) it complains that there's no JDK specified. After I manually go to project structure and switch jsTest module SDK from Kotlin SDK that it uses by default to "Project SDK 15", it stops, but then a new problem happens:
Error: Unable to initialize main class io.kotest.launcher.LauncherKt
Caused by: java.lang.NoClassDefFoundError: io/kotest/core/engine/TestEngineListener
each time I try to launch a test. Also i've checked, io.kotest.core.engine.TestEngineListener exists and can be accessed, while io.kotest.launcher.LauncherKt does not
What I might be doing wrong?

How to import a file from another directory in Kotlin?

I have a gradle kotlin project, and I'm generating a kotlin file from a Rust project, so it ends up in a totally different place with no gradle project structure, etc.
How do I import this file into my gradle project?
It has its own package but it's a completely standalone file. This is my gradle file:
rootProject.name = "my_project"
include("app")
It's a desktop project, NOT android.
My build.gradle.kts:
plugins {
// Apply the org.jetbrains.kotlin.jvm Plugin to add support for Kotlin.
id("org.jetbrains.kotlin.jvm") version "1.5.31"
// Apply the application plugin to add support for building a CLI application in Java.
application
}
repositories {
// Use Maven Central for resolving dependencies.
mavenCentral()
}
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")
// This dependency is used by the application.
implementation("com.google.guava:guava:30.1.1-jre")
// Use the Kotlin test library.
testImplementation("org.jetbrains.kotlin:kotlin-test")
// Use the Kotlin JUnit integration.
testImplementation("org.jetbrains.kotlin:kotlin-test-junit")
}
application {
// Define the main class for the application.
mainClass.set("my_project.ffi.AppKt")
}
Adding the following code to your build.gradle.kts should do the trick (tested with Gradle 7.3.2):
// TODO: replace this dummy task with the task from your Rust project which
// generates the Kotlin source directory. Make sure that the generated
// directory (with the Kotlin file(s)) is the task output directory.
val rustTask by tasks.registering(Copy::class) {
// To test this, I had simply put a Kotlin file into this "somewhere"
// directory.
from("somewhere")
into(temporaryDir)
}
sourceSets {
main {
java {
srcDir(rustTask)
}
}
}
tasks {
compileKotlin {
dependsOn(rustTask)
}
}
So, we’re simply adding the generated sources as an additional source directory to the default SourceSet which is consumed by the compileKotlin task. In addition, we make sure that the sources are generated before compileKotlin runs.

Unable to resolve cinterop IOS import in Kotlin Multiplatform

I have followed the Kotlin documentation for adding iOS dependencies. In my case the dependency is a pre-compiled framework provided through a third party. So I have followed the case for framework without cocoapod.
I placed my MyFramework.def file in /src
language = Objective-C
modules = MyFramework
package = MyFramework
Then I added the following to the build.gradle.kts in the Kotlin object
```
ios {
binaries {
framework {
baseName = "shared"
}
}
}
iosArm64() {
compilations.getByName("main") {
val JWBLe by cinterops.creating {
// Path to .def file
defFile("src/nativeInterop/cinterop/MyFramework.def")
compilerOpts("-framework", "MyFramework", "-F/Users/user/Projects/MyFramework/ios/SDK")
}
}
binaries.all {
// Tell the linker where the framework is located.
linkerOpts("-framework", "MyFramework", "-F/Users/user/Projects/MyFramework/ios/SDK")
}
}
sourceSets {
val commonMain by getting
val commonTest by getting {
dependencies {
implementation(kotlin("test-common"))
implementation(kotlin("test-annotations-common"))
}
}
val androidMain by getting {
dependencies {
implementation("com.google.android.material:material:1.2.1")
}
}
val androidTest by getting {
dependencies {
implementation(kotlin("test-junit"))
implementation("junit:junit:4.13")
}
}
val iosMain by getting
val iosTest by getting
}
Then I build the project. The library does indeed get seen and I see that in External Libraries, there is a shared-cinterop-MyFramework.klib
However, when I try to import this package into my code under src/iosMain/kotlin/com.example.testapp.shared/platform.kt
I get unresolved error for the library. It seems like I should also need to add something to sourceSets? But I am unsure.
First of all, I got to notice that the Gradle script is incorrect. In this case, the iosArm64 target was declared twice - by the target shortcut and once again where you configure the cinterop. To avoid this duplication, it would be better to configure cinterop like that:
ios()
val iosArm = targets.getByName("iosArm64") as org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget
// A bit dirty cast, but as I'm sure iosArm64 is the Native target, it should be fine. Needed to make highlighting below work as expected.
iosArm.apply {
compilations.getByName("main") {
val JWBLe by cinterops.creating {
// Path to .def file
defFile("src/nativeInterop/cinterop/MyFramework.def")
compilerOpts("-framework", "MyFramework", "-F/Users/user/Projects/MyFramework/ios/SDK")
}
}
binaries.all {
// Tell the linker where the framework is located.
linkerOpts("-framework", "MyFramework", "-F/Users/user/Projects/MyFramework/ios/SDK")
}
}
However, this adjustment won't help with accessing cinterop bindings from the iosMain. In the current state of commonizer, it can share only platform libraries. So anyway, moving all code utilizing those bindings into the src/iosArm64Main folder is the best option available at the moment. Here go an issue from the official tracker to upvote and subscribe - Support commonization of user-defined libraries.
So after some playing around I found the answer.
The dependency was set for a module of iosArm64 which is not available to the iosMain.
I created another folder src/iosArm64Main and placed the source file there. At that point it was able to resolve the library.

How to share Java code between Android and JVM targets (with Kotlin Multiplatform)?

I am trying to share Java code between Android and JVM targets using Kotlin Multiplatform feature (sample project: https://github.com/dmitrykolesnikovich/accessJavaCode-issue)
Simply saying, ":library1" and ":library2" both are Kotlin multiplatform libraries targeting JVM and Android. ":library2" depends on ":library1". They both uses Kotlin and Java. ":library2" is intended to be dependency of 1) Android application and 2) desktop (JavaFX) application. That's why 1) AAR artifact and 2) JAR artifact both are needed (?) - so I use 1) Android target and 2) JVM target for both ":library1" and ":library2".
The problem is that, when I have Java code in ":library1"
public class JavaCode {} // JavaCode.java
And Kotlin code in ":library2" that depends on ":library1"
class AccessJavaCode : JavaCode() // AccessJavaCode.kt
Android target is OK with recognizing Java but JVM target is not:
> Task :library2:compileKotlinJvm FAILED
e: AccessJavaCode.kt: (3, 38): Unresolved reference: JavaCode
In gradle config I define two plugins: kotlin-multiplatform and com.android.library:
apply plugin: "kotlin-multiplatform"
apply plugin: "com.android.library"
kotlin {
targets {
jvm()
android()
}
sourceSets {
jvmMain {
dependencies {
api kotlin("stdlib-common")
api kotlin("stdlib-jdk8")
}
}
androidMain {
dependsOn jvmMain
}
}
}
android {
compileSdkVersion 28
sourceSets {
main {
java.srcDirs += "src/jvmMain/kotlin" // Android target recognizes Java with this
manifest.srcFile "src/androidMain/AndroidManifest.xml"
}
}
}
I am pretty sure it’s something simple with my gradle file. Many thanks for your help guys.
~~~~ EDIT ~~~~
Another workaround the issue without losing the ability to generate an android archive .aar for the library1 would be to make a new version of this same library depending on precompiled artefacts of a splitted version of the original library1.
So you would end up with a multi-module gradle project, something like this:
library1-jvm with java plugin enabled
library1-android with android plugin enabled
library1 which will depends on prebuilt library1-jvm.jar and library1-android.aar
You could use whatever you prefer to publish those artefacts, but a local maven repo should work just fine!
That would mean replacing:
kotlin {
targets {
jvm()
android()
}
sourceSets {
jvmMain {
dependencies {
api kotlin("stdlib-common")
api kotlin("stdlib-jdk8")
}
}
androidMain {
dependsOn jvmMain
}
}
}
with:
kotlin {
targets {
jvm()
android()
}
sourceSets {
jvmMain {
dependencies {
api kotlin("stdlib-common")
api kotlin("stdlib-jdk8")
api "com.company:library-jvm:1.0.0"
}
}
androidMain {
dependsOn jvmMain
dependencies {
api "com.company:library-android:1.0.0"
}
}
}
}
That way, you don't need the java plugin at all in the final library1, because all the java code will already be built in a separate step.
Hence library1 could keep both the JVM and Android targets
~~~~~~~~~~~~~
In order to fix your issue, you need to:
Split your build.gradle configuration in order to have one config per library, this will be needed because you cannot enable the java plugin and the android at the same time for the same Gradle project, or you will end up with the following Error: The 'java' plugin has been applied, but it is not compatible with the Android plugins
Enable the java plugin in your library1 project if you want your JVM target to recognize your Java source files.
The Java source files need to be placed in the sibling directories java of the kotlin source roots.
More infos: Kotlin docs for java-support-in-jvm-targets
I also created a pull request solving your issue.
The downside of this approach is that you will not be able to generate an android archive .aar for the library1, but I guess using the java archive .jar in your android project should not be a problem at all.
library1/build.gradle:
apply plugin: "kotlin-multiplatform"
kotlin {
jvm {
withJava()
}
sourceSets {
jvmMain {
dependencies {
api kotlin("stdlib-common")
api kotlin("stdlib-jdk8")
}
}
}
}
library2/build.gradle:
apply plugin: "kotlin-multiplatform"
apply plugin: "com.android.library"
kotlin{
jvm()
android()
sourceSets {
jvmMain.dependencies {
api project(":library1")
}
androidMain {
dependsOn jvmMain
}
}
}
android {
compileSdkVersion 28
sourceSets {
main {
java.srcDirs += "src/jvmMain/kotlin"
manifest.srcFile "src/androidMain/AndroidManifest.xml"
}
}
}

Create fat jar from kotlin multiplatform project

I recently switched from old 1.2 multiplatform into 1.3. Difference is, there's one one build.gradle file per multiplatform module (I got 5 of them) so a lot less configuration.
However I can't seem to be able to configure creating runnable fat jar with all dependencies from jvm platform.
I used to use standard "application" plugin in my jvm project and jar task, but that does not work anymore. I found there's "jvmJar" task and I modified it (set Main-class), but created jar doesn't contain dependencies and crashes on ClassNotFoundException. How do I do it?
This is what I have now:
jvm() {
jvmJar {
manifest {
attributes 'Main-Class': 'eu.xx.Runner'
}
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
}
}
I did hit that bump and used this work around.
1. Restructure your project
Lets call your project Project.
create another submodule say subA, which will have the gradle notation Project:subA
now, subA has your multiplatform code in it (It is the gradle project with apply :kotlin-multiplafrom) in its build.gradle
2. Add Another submodule
create another submodule which targets only jvm say subB, which will have the gradle notation Project:subB
So, subB will have plugins: 'application' and 'org.jetbrains.kotlin.jvm'
3. Add your module as a gradle dependency (see my build.gradle)
plugins {
id 'org.jetbrains.kotlin.jvm' version '1.3.31'
id "application"
}
apply plugin: "kotlinx-serialization"
group 'tz.or.self'
version '0.0.0'
mainClassName = "com.example.MainKt"
sourceCompatibility = 1.8
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
dependencies {
implementation project(':subA')
}
you can proceed and build subB as you would a regular java project or even use the existing plugins, it will work
Got it working with the multiplatform plugin in kotlin 1.3.61:
The following works for a main file in src/jvmMain/kotlin/com/example/Hello.kt
Hello.kt must also specify its package as package com.example
I configured my jvm target in this way:
kotlin {
targets {
jvm()
configure([jvm]) {
withJava()
jvmJar {
manifest {
attributes 'Main-Class': 'com.example.HelloKt'
}
from { configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } }
}
}
}
}
Got it to work with a slightly modified version of what luca992 did:
kotlin {
jvm() {
withJava()
jvmJar {
manifest {
attributes 'Main-Class': 'sample.MainKt'
}
from { configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } }
}
}
...
}
The only way to get gradle/multiplatform working appears to be endless trial and error; It's a nightmare, it's not being built as a "build" system so much as a "build system"; to put it another way, these two tools (together or in isolation) are a means of implementing only a single software development life cycle that the plugin maker intended, however, if you've engineered a desired software lifecycle and CI/CD system and now your trying to implement that engineering, it will be MUCH harder to do it with these tools than it would be to do it with scripts, code or maven. There are a number of reasons for this:
Massive changing in coding convention due to the plugin makers only exposing bar minimum configurability, probably only giving access to the things they need for their own personal project.
Very poor documentation updates; Kotlin, gradle and plugins are changing so rapidly I have begun to seriously question the usefulness of these tools.
Thus, at the time of writing this seems to be the correct syntax to use when using kotlin 1.3.72, multiplatform 1.3.72, ktor 1.3.2 and gradle 6.2.2 (using the kts format).
Note the fatJar seems to assemble correctly but won't run, it can't find the class, so I included the second runLocally task I've been using in the mean time.
This isn't a complete solution so I hate posting it on here, but from what I can tell... it is the most complete and up to date solution I can find documented anywhere.
//Import variables from gradle.properties
val environment: String by project
val kotlinVersion: String by project
val ktorVersion: String by project
val kotlinExposedVersion: String by project
val mySqlConnectorVersion: String by project
val logbackVersion: String by project
val romeToolsVersion: String by project
val klaxonVersion: String by project
val kotlinLoggingVersion: String by project
val skrapeItVersion: String by project
val jsoupVersion: String by project
val devWebApiServer: String by project
val devWebApiServerVersion: String by project
//Build File Configuration
plugins {
java
kotlin("multiplatform") version "1.3.72"
}
group = "com.app"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
jcenter()
jcenter {
url = uri("https://kotlin.bintray.com/kotlin-js-wrappers")
}
maven {
url = uri("https://jitpack.io")
}
}
//Multiplatform Configuration
kotlin {
jvm {
compilations {
val main = getByName("main")
tasks {
register<Jar>("buildFatJar") {
group = "application"
manifest {
attributes["Implementation-Title"] = "Gradle Jar File Example"
attributes["Implementation-Version"] = archiveVersion
attributes["Main-Class"] = "com.app.BackendAppKt"
}
archiveBaseName.set("${project.name}-fat")
from(main.output.classesDirs, main.compileDependencyFiles)
with(jar.get() as CopySpec)
}
register<JavaExec>("runLocally") {
group = "application"
setMain("com.app.BackendAppKt")
classpath = main.output.classesDirs
classpath += main.compileDependencyFiles
}
}
}
}
js {
browser { EXCLUDED FOR LENGTH }
}
sourceSets { EXCLUDED FOR LENGTH }
}