kotlin multiplatform shadow fat jar and runShadow task? - gradle

I have a fairly standard kotlin multiplatform (mpp) build.gradle.kts that uses application plugin and com.github.johnrengelman.shadow
I succeeded to create an java -jar executable fat jar:
new solution:
EDIT:
I extended a line to #Pylyp Dukhov solution:
classpath += files("$buildDir/processedResources/jvm/main")
tasks {
named<JavaExec>("run") {
standardInput = System.`in`
classpath += objects.fileCollection().from(
named("compileKotlinJvm"),
configurations.named("jvmRuntimeClasspath")
)
classpath += files("$buildDir/processedResources/jvm/main")
}
shadowJar {
manifest { attributes["Main-Class"] = theMainClass }
archiveClassifier.set("fat")
val jvmJar = named<org.gradle.jvm.tasks.Jar>("jvmJar").get()
from(jvmJar.archiveFile)
configurations.add(project.configurations.named("jvmRuntimeClasspath").get())
}
}
old solution:
application {
mainClass.set(theMainClass)
}
tasks {
val shadowCreate by creating(com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar::class) {
manifest { attributes["Main-Class"] = theMainClass }
archiveClassifier.set("fat")
mergeServiceFiles()
from(kotlin.jvm().compilations.getByName("main").output)
configurations = mutableListOf(kotlin.jvm().compilations.getByName("main").compileDependencyFiles as Configuration)
}
val build by existing {
dependsOn(shadowCreate)
}
}
but now I struggle on how to get the application gradle run task respectively the shadow gradle runShadow task to execute correctly.
Anybody Any Ideas (kotlindsl) ?

I'm using the following:
tasks.named<JavaExec>("run") {
classpath += objects.fileCollection().from(
tasks.named("compileKotlinJvm"),
configurations.named("jvmRuntimeClasspath")
)
}

Related

Child process exited with code 1 LibGDX jPackageImage task

I am using jpackage to convert my libgdx game to an executable file. I am following this tutorial to do so. The jpackageImage task works perfectly fine but when the exe is created and I run it, it doesn't run but rather gives me an error: Child process exited with code 1 I am unaware what is causing this.
I am on windows 11 and im using JDK 18.0.1.1.
The JDK is set to JAVA_HOME which is set to the correct PATH.
I am using Badass-Runtime plugin as well which is defined in the first line of my build.gradle file.
Here is my build.gradle file for desktop:
plugins { id 'org.beryx.runtime' version '1.8.4' }
sourceCompatibility = 1.7
sourceSets.main.java.srcDirs = ["src/"]
sourceSets.main.resources.srcDirs = ["../core/assets"]
mainClassName = "com.mygdx.game.desktop.DesktopLauncher"
def osName = System.getProperty('os.name').toLowerCase(Locale.ROOT)
project.ext.assetsDir = new File("../core/assets")
task runGame(dependsOn: classes, type: JavaExec) {
main = project.mainClassName
classpath = sourceSets.main.runtimeClasspath
standardInput = System.in
workingDir = project.assetsDir
ignoreExitValue = true
}
task debug(dependsOn: classes, type: JavaExec) {
main = project.mainClassName
classpath = sourceSets.main.runtimeClasspath
standardInput = System.in
workingDir = project.assetsDir
ignoreExitValue = true
debug = true
}
task dist(type: Jar) {
manifest {
attributes 'Main-Class': project.mainClassName
}
dependsOn configurations.runtimeClasspath
from {
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
with jar
destinationDirectory = file("$buildDir/lib")
}
jpackageImage.dependsOn dist
dist.dependsOn classes
eclipse.project.name = appName + "-desktop"
runtime {
options = ['--strip-debug',
'--compress', '2',
'--no-header-files',
'--no-man-pages',
'--strip-native-commands',
'--vm', 'server']
modules = ['java.base',
'java.desktop',
'jdk.unsupported']
distDir = file(buildDir)
jpackage {
jpackageHome = 'C:\\Users\\pc\\.jdks\\openjdk-18.0.1.1'
mainJar = dist.archiveFileName.get()
if (osName.contains('windows')) {
imageOptions = ["--icon", file("../icons/icon.ico")]
} else if (osName.contains('linux')) {
imageOptions = ["--icon", file("../icons/icon.png")]
} else if (osName.contains('mac')) {
imageOptions = ["--icon", file("../icons/icon.icns")]
}
}
}
Is it this bug? bugs.openjdk.org/browse/JDK-8284067 which triggers because your code exits with 1. Try doing with System.exit(0); , there is a workaround listed as well.

How do I publish a second library from another sourceset in gradle?

I have this tlib sourceset
sourceSets {
val main by getting
val tlib by creating {
compileClasspath += main.output
runtimeClasspath += main.output
}
val test by getting {
compileClasspath += tlib.output
runtimeClasspath += tlib.output
}
}
configurations {
val tlibCompile by getting {
extendsFrom(configurations["implementation"])
}
}
I am imagining something like this, but this is not complete
publishing {
publications {
val tlibSourcesJar by tasks.registering(Jar::class) {
classifier = "sources"
from(sourceSets["tlib"].allSource)
}
register("mavenTLib", MavenPublication::class) {
from(components["tlib"])
artifact(tlibSourcesJar.get())
}
}
}
but I get
Could not create domain object 'mavenTLib' (MavenPublication)
> SoftwareComponentInternal with name 'tlib' not found.
How can I publish my test lib separately from my main lib?
this works to an extent but is probably not the best way to do it
sourceSets {
val main by getting
val tlib by creating {
compileClasspath += main.output
runtimeClasspath += main.output
}
val test by getting {
compileClasspath += tlib.output
runtimeClasspath += tlib.output
}
}
configurations {
val tlibCompile by getting {
extendsFrom(configurations["implementation"])
}
}
publishing {
publications {
val tlibJar by tasks.registering(Jar::class) {
from(sourceSets["tlib"].output)
}
val tlibSourcesJar by tasks.registering(Jar::class) {
archiveClassifier.set("sources")
from(sourceSets["tlib"].allSource)
}
register("mavenTLib", MavenPublication::class) {
artifactId = "phg-entity-tlib"
artifact(tlibJar.get())
artifact(tlibSourcesJar.get())
}
}
}
I have an example here, unfortunately it is written in Groovy, and I am not yet familiar with the Kotlin way of doing it.
Maybe it still helps:
https://github.com/thokari/gradle-workshop/blob/master/examples/09-multiple-artifacts/build.gradle
The most relevant part is probably this:
outputArchives.each { outputArchive ->
String logicalName = outputArchive.camelCase()
// Add archiving tasks.
// These could be anything with type AbstractArchiveTask (e.g. War, Zip).
task("${logicalName}Jar", type: Jar) { from configurations."${logicalName}Compile" }
task("${logicalName}SourceJar", type: Jar) { from sourceSets."${logicalName}".java }
// Configure the publishing extension added by the 'maven-publish' plugin.
// For every combination of publication and repository, a task with name
// publish<publicationName>PublicationTo<repositoryName>Repository is created.
// The task 'publish' is a shortcut, depending on each one of them.
publishing {
publications {
// Create a publication by calling its name and type.
"${logicalName}"(MavenPublication) {
// Override the artifact id, which defaults to the project name.
artifactId = outputArchive.dashSeparated()
// Publish the artifacts created by the archiving tasks.
artifact tasks."${logicalName}Jar"
artifact(tasks."${logicalName}SourceJar") { classifier 'source' }
}
}
}
}
I also never figured out how to make use of this SoftwareComponent concept. I solved this by calling the artifact method on the archiving tasks that I created, instead of using from(component), I would think this could also be done in Kotlin.

Kotlin JS built as JVM project resources with Gradle

Is it possible (if so, how I can do it?) using Gradle to compile Kotlin JS sources and then put them in Kotlin JVM project as jar resources?
I've used this build.gradle script once to build a jar with those compiled resources:
import com.eriwen.gradle.js.tasks.MinifyJsTask
plugins {
id "com.eriwen.gradle.js" version "2.12.0"
}
def outDir = new File(buildDir, 'out')
def out = new File(outDir, 'name.js')
def min = new File(outDir, 'name.min.js')
compileKotlin2Js {
kotlinOptions {
outputFile = out
metaInfo = false
noStdlib = true
sourceMap = true
}
}
task minifyKotlinJs(type : MinifyJsTask) {
source = out
dest = min
}
jar {
from (outDir) {
into("your/package/name")
include '*.js', '*.map'
}
include 'META-INF', 'your'
}
minifyKotlinJs.dependsOn classes
jar.dependsOn minifyKotlinJs

Defining custom ‘build’ task is deprecated when using standard lifecycle plugin has been deprecated and is scheduled to be removed in Gradle 3.0

I am facing an issue in my build.gradle script My script is bascially generatiing the POM file and then copy the artifact to other location as well under build/lib with different name.The issue which I am facing How to call the below build task beacuse it is generating the error.I am using gradle 2.3
Error:"Defining custom ‘build’ task is deprecated when using standard lifecycle plugin has been deprecated and is scheduled to be removed in Gradle 3.0"
My task build will build the artifact and then generate the POM and move the artifact to different location but I am getting below error.
My full script is
apply plugin: 'cpp'
apply plugin: 'java'
//-- set the group for publishing
group = 'com.tr.anal'
/**
* Initializing GAVC settings
*/
def buildProperties = new Properties()
file("version.properties").withInputStream {
stream -> buildProperties.load(stream)
}
//add the jenkins build version to the version
def env = System.getenv()
if (env["BUILD_NUMBER"]) buildProperties.analBuildVersion += "_${env["BUILD_NUMBER"]}"
version = buildProperties.analBuildVersion
println "${version}"
//name is set in the settings.gradle file
group = "com.t.anal"
version = buildProperties.analBuildVersion
println "Building ${project.group}:${project.name}:${project.version}"
repositories {
maven {
url "http://cm.thon.com:900000/artifactory/libs-snapshot-local"
}
maven {
url "http://cm.thon.com:9000000/artifactory/libs-release"
}
}
dependencies {
compile ([
"com.tr.anal:analytics-engine-common:4.+"
])
}
model {
repositories {
libs(PrebuiltLibraries) {
jdk {
headers.srcDirs "${System.properties['java.home']}/../include",
"${System.properties['java.home']}/../include/win32",
"${System.properties['java.home']}/../include/darwin",
"${System.properties['java.home']}/../include/linux"
}
}
}
}
model {
platforms {
x64 { architecture "x86_64" }
x86 { architecture "x86" }
}
}
model {
components {
main(NativeLibrarySpec) {
sources {
cpp {
source {
lib library: 'main', linkage: 'static'
lib library: 'jdk', linkage: 'api'
srcDir "src/main/c++/native"
include "**/JniSupport.cpp"
include "**/DiseaseStagingJni.cpp"
}
}
}
}
}
}
def nativeHeadersDir = file("$buildDir/nativeHeaders")
//def compilePath = configurations.compile.resolve().collect {it.absolutePath}.join(";")
binaries.all {
// Define toolchain-specific compiler and linker options
if (toolChain in Gcc) {
cppCompiler.args "-I${nativeHeadersDir}"
cppCompiler.args "-g"
linker.args '-Xlinker', '-shared -LNativeJNI/src/main/resources/DSresources/DSLib -lds64 -Wl'
}
}
//def nativeHeadersDir = file("$buildDir/nativeHeaders")
task nativeHeaders {
// def nativeHeadersDir = file("$buildDir/nativeHeaders")
def outputFile = file("$nativeHeadersDir/DiseaseStagingJniWrapper.h")
def classes = [
'com.truvenhealth.analyticsengine.common.diseasestaging.DiseaseStagingJniWrapper'
]
inputs.files sourceSets.main.output
inputs.property('classes', classes)
outputs.file outputFile
doLast {
outputFile.parentFile.mkdirs()
def compilePath = configurations.compile.resolve().collect {it.absolutePath}.join(":")
println "Using Compile Path: ${compilePath}"
exec {
executable org.gradle.internal.jvm.Jvm.current().getExecutable('javah')
args '-o', outputFile
args '-classpath', compilePath
args classes
}
}
}
tasks.withType(CppCompile) { task ->
task.dependsOn nativeHeaders
}
/*****************************
* Packaging
*****************************/
apply plugin: "maven"
// Workaround for Jenkins-Artifactory plugin not picking up the POM file
def pomFile = file("${buildDir}/libs/${archivesBaseName.toLowerCase()}-${version}.pom")
task newPom << {
pom {
project {
groupId project.group
artifactId project.name
version project.version
description = "Configuration Management Gradle Plugin"
}
}.writeTo(pomFile)
}
//disabling the install task since we're not using maven for real
install.enabled = false
//for publishing to artifactory via jenkins
if(project.hasProperty('artifactoryPublish')) {
artifactoryPublish {
mavenDescriptor pomFile
}
}
def filechange = file("build/libs/NativeJNI-${project.version}.so")
task copyfile(type: Copy) {
from 'build/binaries/mainSharedLibrary'
into 'build/libs'
include('libmain.so')
rename ('libmain.so', "$filechange")
}
//build.dependsOn copyfile
task build (dependsOn: ["newPom","copyfile"]) << {
println "build in progress"
}
def someFile = file("build/libs/NativeJNI-${project.version}.so")
artifacts {
archives someFile
}
Looks like this was a bug in 3.0,
https://github.com/GradleFx/GradleFx/issues/235

Gradle build - Maven Modello

I have a Maven build which uses maven-modello (1.4) to generate Java classes/XSD's etc. from an description file (modello file). I'm searching for a possible solution in Gradle to solve the same problem.
I haven't test it, but can something like that do the trick:
import org.codehaus.modello.Modello
// Dependencies
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.codehaus.modello:modello-maven-plugin:1.5'
}
}
// Execution
task modello << {
buildDir.mkdirs()
file("$projectDir/models").eachFile { modelFile ->
if (modelFile.name.endsWith('.mdo')) {
new Modello().generate(modelFile.newReader(), generator, parameters)
}
}
}
// Configuration
modello.ext {
generator = 'java'
parameters = new Properties()
parameters.'modello.output.directory' = buildDir.absoluteFile
parameters.'modello.version' = '1.5'
parameters.'modello.package.with.version' = false
parameters.'modello.output.useJava5' = true
parameters.'modello.output.encoding' = 'UTF-8'
}

Resources