Gradle add compileClasspath to configurations in ShadowJar (kotlin) - gradle

Shadowjar's docs say to do this:
shadowJar {
configurations = [project.configurations.compileClasspath]
}
This appears to be in Groovy. If I run this in my Kotlin based gradle project, I get the following error:
Type mismatch:
inferred type is
Array<NamedDomainObjectProvider<Configuration>>, but
(Mutable)List<FileCollection!>! was expected
How can I perform this in Kotlin?

The equivalent would be:
tasks {
shadowJar {
configurations = listOf(project.configurations.compileClasspath.get())
}
}
The call to .get() is required because the return is NamedDomainObjectProvider<Configuration>. The Shadow plugin does not appear to support the lazy properties Gradle provides.

Related

Configure plugin in separate file using Kotlin DSL

to differenciate diferent plugins configurations, I use separate files.
For example:
./build.gradle.kts
./detekt.gradle.kts
./settings.gradle.kts
./module1
./module2
...
In the root build.gradle.kts I have this:
plugins {
id("io.gitlab.arturbosch.detekt") version DependencyVersion.Detekt
}
buildscript {
dependencies {
classpath(io.gitlab.arturbosch.detekt:detekt-gradle-plugin:1.1.1)
}
}
And to configure it I go to the detekt.gradle.kts and put:
apply(plugin = "io.gitlab.arturbosch.detekt")
detekt {
// configure
}
But detekt lambda is not found. Also tried with:
apply(plugin = "io.gitlab.arturbosch.detekt")
configure<io.gitlab.arturbosch.detekt.Detekt> {
// configure
}
But it doesn't find .Detekt.
With JaCoCo I haven't got any problems using the second approach, but it doesn't work with Detekt or SonarQube.
How can I configure plugins in a separate file?
Thanks.
Try something like below. I have declared a plugin "sonarqube" in my main gradle. I then apply the file sonar.gradle.kts towards the end of the build.gradle.kts file.
build.gradle.kts:
plugins {
id("org.sonarqube") version "2.8" apply false
}
...
apply(from="$rootDir/gradle/includes/sonar.gradle.kts")
gradle/includes/sonar.gradle.kts:
apply(plugin="org.sonarqube")
Using a setup like above, I can then run "gradle sonarqube"
I faced a similar issue. Everything that you need to do is to call
configure<io.gitlab.arturbosch.detekt.extensions.DetektExtension> {
// configure
}
More info, you can find here: https://docs.gradle.org/current/userguide/migrating_from_groovy_to_kotlin_dsl.html#configuring-plugins

How to lazily get main sourceSets in Gradle

I need to configure sources jar for all of my subprojects. I have the following subprojects configuration defined:
subprojects {
apply(plugin = "java-library")
val sourcesJar = tasks.registering(Jar::class) {
archiveClassifier.set("sources")
from(the<SourceSetContainer>().named("main").get().allJava)
}
tasks.named("assemble") {
dependsOn(sourcesJar)
}
}
When I try to run ./gradlew tasks I receive an exception in my subproject saying that:
Extension of type 'SourceSetContainer' does not exist. Currently registered extension types: [ExtraPropertiesExtension]
My assumption is that the access to get() method of the extension causes problems but without that I cannot refer to the allJava sources that I need. So how to achieve desired result by using configuration avoidance API?
Running on Gradle 5.2.1 with Kotlin DSL.
I found working solution. The problem is that when you call the<T>() function it is taken from the Task type which is why it complains about absent extension. The solution is to call the<T>() function on project instance like this:
subprojects {
apply {
plugin<JavaLibraryPlugin>()
}
val sourcesJar by tasks.registering(Jar::class) {
archiveClassifier.set("sources")
from(
// take extension from project instance
project.the<SourceSetContainer>().named("main").get().allJava
)
}
}

Gradle Kotlin DSL equivalent for Groovy DSL 'run'?

I am trying to build a simple JavaFX 11 program with Kotlin and Java 11, using Gradle, following the instructions here. However, this page uses Gradle's Groovy DSL, and I am trying to use the Kotlin DSL. Surprisingly, my Google searches have not turned up a document that maps each Groovy construct to its equivalent Kotlin construct or explains in general how to convert Groovy DSL code to equivalent Kotlin DSL code. (This seems like a big oversight in the Gradle documentation!).
In particular, this document contains the following Groovy code:
compileJava {
doFirst {
options.compilerArgs = [
'--module-path', classpath.asPath,
'--add-modules', 'javafx.controls'
]
}
}
run {
doFirst {
jvmArgs = [
'--module-path', classpath.asPath,
'--add-modules', 'javafx.controls'
]
}
}
As far as I can tell, the Kotlin equivalent to the first part appears to be:
tasks.withType<JavaCompile> {
options.compilerArgs.addAll(arrayOf(
"--module-path", classpath.asPath,
"--add-modules", "javafx.controls"
))
}
However, I have not been able to figure out what the Kotlin DSL equivalent to the second part is. Note that 'run' is a standard function extension in Kotlin's standard library, so it does not appear that the Kotlin version of this code can use the name 'run' for the same purpose in the Kotlin DSL.
(Note: I considered trying to use a plugin for the JavaFX support (as described by this page, for instance), but the plugin seems quite complicated to use, and I already am having enough problems with the number of complications in this project that I am hesitant to introduce a very-lightly-documented open-source plugin into the mix. I really am trying to produce the simplest possible "Hello, World" program in JavaFX/Gradle at the moment, and this has so far seemed surprisingly difficult.).
Any help would be appreciated.
Using the configuration avoidance APIs, the equivalent to the second block is:
tasks.named<JavaExec>("run") {
doFirst {
jvmArgs = listOf("--module-path", classpath.asPath,"--add-modules", "javafx.controls")
}
}
The key is that run has the JavaExec type, which like any task's type can be discovered by creating a task to print the class of the task that you then run:
tasks.register("getName") {
doFirst {
print("Class name: ${tasks["run"].javaClass}")
}
}
Note that as your JavaFX application grows, you will need to specify additional modules like this:
tasks.named<JavaExec>("run") {
doFirst {
jvmArgs = listOf("--module-path", classpath.asPath,
"--add-modules", "javafx.base,javafx.controls,javafx.graphics")
}
}
Surprisingly, my Google searches have not turned up a document that maps each Groovy construct to its equivalent Kotlin construct or explains in general how to convert Groovy DSL code to equivalent Kotlin DSL code.
Please have a look at https://guides.gradle.org/migrating-build-logic-from-groovy-to-kotlin/ and esp. the Configuring tasks section. According to that, I'd say the Kotlin DSL equivalent is
tasks.named<JavaExec>("run").doFirst {
jvmArgs = listOf('--module-path', classpath.asPath, '--add-modules', 'javafx.controls')
}
With Gradle 5.0 and kotlin-dsl 1.0, tasks that are registered or created by plugins can be statically accessed through the tasks container (TaskContainer. There is this example provided in the release notes:
plugins {
java
}
tasks {
named<Test>("test") {
testLogging.showStacktraces = true
}
}
you can now write:
plugins {
java
}
tasks {
test {
testLogging.showStacktraces = true
}
}
For your example, you are most likely using the application plugin, which registers the run task so you can configure it in a similar matter. One issue to be aware of is that run clashes with the Kotlin stdlib run method so you need to apply some workaround to make sure it gets invoked (see gradle/kotlin-dsl/issues/1175)
tasks {
compileJava {
doFirst {
jvmArgs = listOf("--module-path", classpath.asPath,
"--add-modules", "javafx.base,javafx.controls,javafx.graphics")
}
}
(run) {
doFirst {
jvmArgs = listOf(
"--module-path", classpath.asPath,
"--add-modules", "javafx.controls"
)
}
}
}
The other answers show how you can use the name, type, or combination to query the container for specific tasks.

Kotlin and Gradle - Reading from stdio

I am trying to execute my Kotlin class using the command:
./gradlew -q run < src/main/kotlin/samples/input.txt
Here is my HelloWorld.kt class:
package samples
fun main(args: Array<String>) {
println("Hello, world!")
val lineRead = readLine()
println(lineRead)
}
Here is my build.gradle.kts:
plugins {
kotlin("jvm")
application
}
application {
mainClassName = "samples.HelloWorldKt"
}
dependencies {
compile(kotlin("stdlib"))
}
repositories {
jcenter()
}
The code executes, but the data contained inside the input.txt file is not displayed. Here is the output I get:
Hello, world!
null
I want to be able to execute the gradlew command above and the input.txt stream be redirected to stdio. I can easily do that in C++. Once I compile my .cpp file, I can run:
./my_code < input.txt
and it executes as expected.
How can I achieve the same thing with Kotlin and Gradle?
Update: Based on this answer, I've tried adding this to build.gradle.kts but it is not a valid syntax:
AjahnCharles suggestion about run { standardInput = System.in } is correct, but to port it to kotlin-dsl you need a different syntax.
run in this case is the task name and you configure existing task of application plugin.
To configure existing task in kotlin-dsl you should use one of this ways:
val run by tasks.getting(JavaExec::class) {
standardInput = System.`in`
}
or
val run: JavaExec by tasks
run.standardInput = System.`in`
The upcoming version of Gradle 4.3 should provide API for plugin writers to read user input.
The reason of difference between of Groovy and Kotlin in this case because Groovy uses dynamic types, but in Kotlin you must specify task type to have autocompletion and just to compile config script
I finally settled on this (Gradle 7.1.1):
plugins {
application
}
tasks.getByName("run", JavaExec::class) {
standardInput = System.`in`
}
I don't know enough Kotlin yet to judge whether this is equivalent to https://stackoverflow.com/a/46662535/253921.
Almost, but this doesn't work :'(
In Theory
My understanding: < input.txt sets the standard input for the gradlew process, but by default this is not forwarded to your program.
You want to add this to your build.gradle.kts:
run {
standardInput = System.`in`
}
Sources:
https://discuss.gradle.org/t/why-doesnt-system-in-read-block-when-im-using-gradle/3308/2
https://discuss.gradle.org/t/how-can-i-execute-a-java-application-that-asks-for-user-input/3264
In Practice
These build configs look about the same to me, yet Groovy works and Kotlin doesn't. I'm starting to think that the Gradle Kotlin DSL doesn't support the standardInput term yet :/
Here's my working Groovy version if that's any help:
apply plugin: 'kotlin'
apply plugin: 'application'
buildscript {
ext.kotlin_version = '1.1.4'
repositories {
jcenter()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
repositories {
jcenter()
}
dependencies {
// api => exported to consumers (found on their compile classpath)
// implementation => used internally (not exposed to consumers)
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}
mainClassName = "samples.HelloWorldKt"
run {
standardInput = System.in
}

Gradle compileKotlin includeRuntime not adding runtime to jar

I have a Kotlin Gradle project, and I would like to include Kotlin's runtime and stdlib in the jar file. I'm currently using this, but it's not including the runtime or stdlib when I build the project using the build.gradle configuration.
compileKotlin {
kotlinOptions {
includeRuntime = true
noStdlib = false
}
}
This is the Gradle code I'm using to include the runtime/stdlib in the jar, but it isn't working like I expect it to. Here's the full build.gradle file for some context:
https://github.com/BenWoodworth/CrossPlatformGreeter/blob/bd1da79f36e70e3d88ed871bc35502ecc3a852fb/build.gradle#L35-L43
Kotlin's Gradle documentation seems to indicate that setting kotlinOptions.includeRuntime to true should include the Kotlin runtime in the resulting .jar.
https://kotlinlang.org/docs/reference/using-gradle.html#attributes-specific-for-kotlin
Edit:
This might be related. When I run compileKotlin, I'm getting a couple of warnings related to the runtime:
:compileKotlin
w: Classpath entry points to a non-existent location: <no_path>\lib\kotlin-runtime.jar
BUILD SUCCESSFUL
Here's an alternative I came up with. It'll add the Kotlin runtime and stdlib to the jar using the jar task.
jar {
from {
String[] include = [
"kotlin-runtime-${version_kotlin}.jar",
"kotlin-stdlib-${version_kotlin}.jar"
]
configurations.compile
.findAll { include.contains(it.name) }
.collect { it.isDirectory() ? it : zipTree(it) }
}
}
Gradle Kotlin DSL:
tasks.withType<Jar> {
val include = setOf("kotlin-stdlib-1.4.0.jar")
configurations.runtimeClasspath.get()
.filter { it.name in include }
.map { zipTree(it) }
.also { from(it) }
}
Try this:
Build script
Unpack jar
Add kotlin runtime and rapack it
type gradle packJar to create jar with kotlin runtime in it
or
type gradle runJar to create and run the jar file
build Script

Resources