Unable to use plugin in gradle.kts file - kotlin

i´m trying to get a plugin to have the current version in a gradle kts file. I´m not able to get the apply for some reason, this is my code ->
buildscript {
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
classpath("com.google.code.gson:gson:${rootProject.extra["gson_version"]}")
}
}
plugins {
id("me.tadej.versioning") version "0.2.0"
}
But i´m getting this error ->
"The plugins {} block must not be used here. If you need to apply a plugin imperatively, please use apply() or apply(plugin = "id") instead."
What i´m doing wrong here ?
Thanks!
EDIT:
I tried to write this as:
import com.google.gson.Gson
import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.net.HttpURLConnection
import java.net.URL
plugins {
id("me.tadej.versioning") version "0.2.0"
}
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
classpath("com.google.code.gson:gson:${rootProject.extra["gson_version"]}")
}
And got this error message:
ScriptCompilationException(errors=[ScriptCompilationError(message=Unresolved reference: gson, location=/Users/develop/.gradle/.tmp/gradle-kotlin-dsl-14359683498958959271.tmp/jira.gradle.kts (1:19)), ScriptCompilationError(message=Unresolved reference: classpath, location=/Users/develop/.gradle/.tmp/gradle-kotlin-dsl-14359683498958959271.tmp/jira.gradle.kts (17:5)), ScriptCompilationError(message=Unresolved reference: Gson, location=/Users/develop/.gradle/.tmp/gradle-kotlin-dsl-14359683498958959271.tmp/jira.gradle.kts (50:21)), ScriptCompilationError(message=Unresolved reference: Gson, location=/Users/develop/.gradle/.tmp/gradle-kotlin-dsl-14359683498958959271.tmp/jira.gradle.kts (100:16)), ScriptCompilationError(message=Unresolved reference: it, location=/Users/develop/.gradle/.tmp/gradle-kotlin-dsl-14359683498958959271.tmp/jira.gradle.kts (101:26)), ScriptCompilationError(message=Unresolved reference: it, location=/Users/develop/.gradle/.tmp/gradle-kotlin-dsl-14359683498958959271.tmp/jira.gradle.kts (101:40))])
at org.gradle.kotlin.dsl.support.KotlinCompilerKt.compileKotlinScriptModuleTo(KotlinCompiler.kt:187)
at org.gradle.kotlin.dsl.support.KotlinCompilerKt.compileKotlinScriptToDirectory(KotlinCompiler.kt:148)
at org.gradle.kotlin.dsl.execution.ResidualProgramCompiler$compileScript$1.invoke(ResidualProgramCompiler.kt:708)
at org.gradle.kotlin.dsl.execution.ResidualProgramCompiler$compileScript$1.invoke(ResidualProgramCompiler.kt:85)
at org.gradle.kotlin.dsl.provider.StandardKotlinScriptEvaluator$InterpreterHost$runCompileBuildOperation$1.call(KotlinScriptEvaluator.kt:162)...

Related

protoc ^ Unresolved reference

I am trying to follow this example, and I've read numerous SoF and have tried countless examples of this, including straight from the official plugin page, but I continue to run into problems building a simple protobuf app
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import com.google.protobuf.gradle.protoc // here my editor gives a red ___ to .protobuf.
buildscript {
repositories {
maven {
url = uri("https://plugins.gradle.org/m2/")
}
}
dependencies {
classpath("gradle.plugin.com.google.protobuf:protobuf-gradle-plugin:0.8.18")
}
}
apply(plugin = "com.google.protobuf")
plugins {
id("com.google.protobuf") version "0.8.18"
id("org.jetbrains.kotlin.jvm") version "1.4.31"
application
}
repositories {
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.0-jre")
// Use the Kotlin test library.
testImplementation("org.jetbrains.kotlin:kotlin-test")
// Use the Kotlin JUnit integration.
testImplementation("org.jetbrains.kotlin:kotlin-test-junit")
}
protobuf { // my editor knows nothing about this
protoc {
artifact = "com.google.protobuf:protoc:0.8.14"
}
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "15"
}
}
tasks.withType<Test> {
useJUnitPlatform()
}
application {
// Define the main class for the application.
mainClass.set("io.example.AppKt")
}
Error:
* What went wrong:
Script compilation error:
Line 50: protoc {
^ Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public fun ProtobufConfigurator.protoc(action: ExecutableLocator.() -> Unit): Unit defined in com.google.protobuf.gradle
1 error
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
I think you need the statement import com.google.protobuf.gradle.protobuf first, but I'm not sure it can fix your issue.
There is an example project in the protobuf-gradle-plugin repository which is expected to work fine, I think that it can be helpful for you. they are written in Kotlin DSL also. please refer.
https://github.com/google/protobuf-gradle-plugin/blob/master/examples/exampleKotlinDslProject/build.gradle.kts

IntelliJ missing reference to slf4j in new Ktor project

I started a new Ktor project through their IntelliJ plugin and everything is compiling and running fine with Gradle. However in IntelliJ everything that references the slf4j logger is having a Unresolved reference: ... error.
My import and setting log leve looks like this (sorry my reputation is not high enough to post images):
The project is generated with the following dependencies
// gradle.properties
ktor_version=1.4.0
logback_version=1.2.1
// build.gradle.kts
dependencies {
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version")
implementation("io.ktor:ktor-server-netty:$ktor_version")
implementation("ch.qos.logback:logback-classic:$logback_version")
implementation("io.ktor:ktor-server-core:$ktor_version")
implementation("io.ktor:ktor-auth:$ktor_version")
implementation("io.ktor:ktor-auth-jwt:$ktor_version")
implementation("io.ktor:ktor-jackson:$ktor_version")
testImplementation("io.ktor:ktor-server-tests:$ktor_version")
}
I have tried to add org.slf4j:slf4j-nop:1.7.30 to my dependencies without any luck.
So my questions is, has anyone seen this error before and know if there is a dependency or setting i could change? It is annoying to not have any code completion and errors scattered around the IDE even though it compiles and run fine.
The full application code generated with the Ktor plugin is below if needed:
package com.example
import io.ktor.application.*
import io.ktor.response.*
import io.ktor.request.*
import io.ktor.features.*
import org.slf4j.event.*
import io.ktor.routing.*
import io.ktor.http.*
import io.ktor.auth.*
import com.fasterxml.jackson.databind.*
import io.ktor.jackson.*
fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
#Suppress("unused") // Referenced in application.conf
#kotlin.jvm.JvmOverloads
fun Application.module(testing: Boolean = false) {
install(CallLogging) {
level = Level.INFO
filter { call -> call.request.path().startsWith("/") }
}
install(Authentication) {
}
install(ContentNegotiation) {
jackson {
enable(SerializationFeature.INDENT_OUTPUT)
}
}
routing {
get("/") {
call.respondText("HELLO WORLD!", contentType = ContentType.Text.Plain)
}
get("/json/jackson") {
call.respond(mapOf("hello" to "world"))
}
}
}
This was a caching issue with Gradle and IntelliJ, probably caused from other project dependencies. To IntelliJ the slf4j-api library was empty. Removing the global Gradle cache with rm -rf ~/.gradle/caches and re-download the dependencies solved the issue for me.

Unresolved reference: KotlinCompilerVersion in build.gradle.kts

In build.gradle.kts file, I include this code on the top line. Then I use KotlinCompilerVesion.VERSION below.
import org.jetbrains.kotlin.config.KotlinCompilerVersion
Some code works fine, but some code failed:
It seems like only plugins block can not enable this import.
Here works fine:
dependencies {
Implementation(kotlin("stdlib-jdk7", KotlinCompilerVersion.VERSION))
Implementation(kotlin("test", KotlinCompilerVersion.VERSION))
}
Here always wrong:
plugins {
id("com.android.application")
kotlin("android")
kotlin("android.extensions")
/*
* Error: Unresolved reference: KotlinCompilerVersion
*/
id("kotlinx-serialization") version KotlinCompilerVersion.VERSION
/*
* Error: Unresolved reference: KotlinCompilerVersion
*/
id("kotlinx-serialization") version "$KotlinCompilerVersion.VERSION"
/*
* Error: Unresolved reference: KotlinCompilerVersion
*/
id("kotlinx-serialization") version "${KotlinCompilerVersion.VERSION}"
}
How can I use it correctly in here, without declare an ext.xxxVersion var?
Yes, the syntax of the plugins DSL is limited because Gradle parses it before parsing the rest of the file, which requires the definition to be static (no references to variables, constants, etc., pretty much no code is allowed). See Limitations of the plugins DSL for details.
The way I handle defining Kotlin version only once is by actually using the version I specify in the plugins block as canonical in other sections of the file (I picked this up from this blog post by Simon Wirtz) like so:
import org.jetbrains.kotlin.gradle.plugin.KotlinPluginWrapper
val kotlinVersion = plugins.getPlugin(KotlinPluginWrapper::class.java)
.kotlinPluginVersion
plugins {
kotlin("jvm") version "1.3.30"
}
dependencies {
implementation(platform(kotlin("bom", kotlinVersion)))
implementation(kotlin("stdlib-jdk8"))
}
But yeah, in the plugins block it needs to be static and unfortunately repeated if needed.
Update: I actually just learned it's possible to use constants in the plugins DSL, but they must be defined before Gradle parses the build.gradle.kts file, i.e. from buildSrc. I noticed this in the fuel library. In essence, create buildSrc/build.gradle.kts with the following contents:
plugins {
`kotlin-dsl`
}
repositories {
jcenter()
}
Then create buildSrc/src/main/kotlin/Constants.kt with the following contents:
object Kotlin {
const val version = "1.3.30"
}
And then you'll be able to use the following in your main build.gradle.kts:
plugins {
kotlin("jvm") version Kotlin.version
}

launch is only available since Kotlin 1.3 and cannot be used in Kotlin 1.2

I'm trying to run the simplest example with coroutines:
import kotlinx.coroutines.*
fun main() {
GlobalScope.launch {
delay(1000L)
println("${Thread.currentThread().name}: World")
}
println("${Thread.currentThread().name}: Hello")
Thread.sleep(2000L)
println("${Thread.currentThread().name}: Finish!")
}
And my build.gradle file looks like this:
buildscript {
// Consider moving these values to `gradle.properties`
ext.kotlin_version = '1.3.0-rc-146'
ext.kotlin_gradle_plugin_version = '1.3.0-rc-198'
ext.kotlinx_coroutines = '1.0.0-RC1'
repositories {
maven { url "https://kotlin.bintray.com/kotlin-eap" }
mavenCentral()
jcenter()
google()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.51"
}
}
plugins {
id 'org.jetbrains.kotlin.jvm' version "1.1.51"
}
apply plugin: 'idea'
apply plugin: 'application'
group 'by.kotlin'
version '1.0-SNAPSHOT'
mainClassName = 'MainKt'
repositories {
maven { url "https://kotlin.bintray.com/kotlin-eap" }
mavenCentral()
jcenter()
google()
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation "org.jetbrains.kotlin:kotlin-stdlib-common:$kotlin_version"
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlinx_coroutines"
}
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
But when I run this example, I've got the following errors:
e: ...Main.kt: (6, 17): 'launch(CoroutineContext = ..., CoroutineStart = ..., [ERROR : Bad suspend function in metadata with constructor: Function2]<CoroutineScope, Continuation<Unit>, Any?>): Job' is only available since Kotlin 1.3 and cannot be used in Kotlin 1.2
e: ...Main.kt: (7, 9): Suspend function 'delay' should be called only from a coroutine or another suspend function
e: ...Main.kt: (7, 9): 'delay(Long): Unit' is only available since Kotlin 1.3 and cannot be used in Kotlin 1.2
> Task :compileKotlin FAILED
Why do these errors occur? I'm completely confused, because the first error says that launch "is only available since Kotlin 1.3 and cannot be used in Kotlin 1.2", but I use Kotlin 1.3 in my build.gradle file (in particular, '1.3.0-rc-146')...
UPD
It seems that the reason of problem is in IntelliJ IDEA Settings:
But how to fix it, if the latest language version, which can be selected there, is 1.2, not 1.3?
Make sure you have updated Kotlin to 1.3. You can do this from Preference->Lanugage & Framework->Kotlin Updates
Then change the version of kotlin.jvm plugin to 1.3.0 in gradle. (https://plugins.gradle.org/plugin/org.jetbrains.kotlin.jvm)
plugins {
id 'org.jetbrains.kotlin.jvm' version "1.3.0"
}
And for including coroutines
repositories {
mavenCentral()
}
dependencies {
compile group: 'org.jetbrains.kotlinx', name: 'kotlinx-coroutines-core', version: '1.0.0'
}
It should be fine now.
You must change kotlin plugin version
Your current kotlin plugin version is 1.2.51
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.51"
}
this is correct
buildscript {
ext.kotlin_version = '1.3.0'
ext.kotlin_gradle_plugin_version = '1.3.0'
ext.kotlinx_coroutines = '1.0.0'
repositories {
maven { url "https://kotlin.bintray.com/kotlin-eap" }
mavenCentral()
jcenter()
google()
}
dependencies {
'org.jetbrains.kotlin:kotlin-gradle-plugin:'+kotlin_version
}
}
I solved this by manually updating the Kotlin-IntelliJ Plugin.
First, download the newer version of the Kotlin plugin that is compatible with your version of IntelliJ https://plugins.jetbrains.com/plugin/6954-kotlin/versions/stable
Then in IntelliJ's Settings -> Plugins, click on the settings/gear icon on the top-right side. From there choose Install Plugin from Disk..., choose the zip file you got from the intellij website. Then it will ask you to restart the IDE, and that's it :)
If it has started to occur only recently then chances are two links are generating same file with same name, in this case removing one of your recent file from build.gradle will help you resolving the issue.
In my case this was causing the issue
implementation 'com.miguelcatalan:materialsearchview:1.4.0'
implementation 'com.github.Ferfalk:SimpleSearchView:0.2.0'
After removing first one out of them the issue was resolved.

How to build kotlinx.coroutines in Kotlin/Native (test version 0.23.4-native-1)

This question is a continuation of this thread:
https://github.com/Kotlin/kotlinx.coroutines/issues/246#issuecomment-407023156
I am trying to use org.jetbrains.kotlinx:kotlinx-coroutines-core-native:0.23.4-native-1 in a Kotlin/Native project targeting iOS.
build.gradle:
buildscript {
repositories {
mavenCentral()
maven { url "https://dl.bintray.com/jetbrains/kotlin-native-dependencies" }
}
dependencies {
classpath 'org.jetbrains.kotlin:kotlin-native-gradle-plugin:0.8'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.51"
}
}
apply plugin: 'kotlin-platform-native'
repositories {
jcenter()
mavenCentral()
maven { url "https://kotlin.bintray.com/kotlinx" }
}
sourceSets {
main {
component {
target 'ios_arm32', 'ios_arm64', 'ios_x64'
outputKinds = [KLIBRARY]
}
}
}
dependencies {
expectedBy project(':common')
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core-native:0.23.4-native-1"
}
The kotlinx:kotlinx-coroutines-core-native dependency doesn't seem to work, as the produces build errors like:
error: unresolved reference: coroutines
import kotlinx.coroutines.experimental.*
^
If I manually include the artifact dependencies such as org.jetbrains.kotlinx:kotlinx-coroutines-core-native_release_ios_x64:0.10.3-native, then I get a complier exception:
exception: java.lang.IllegalStateException: Could not find "atomicfu-native"
This error persists, even if I also add org.jetbrains.kotlinx:atomicfu-native:0.10.3-native dependency.
Here is a list of things to check for (I have been through this, and finally made it work) :
Enable Gradle metadata. It's required to retrieve the coroutines dependencies. To do so, add this line in your "settings.gradle" file, after all the "include" instructions :
enableFeaturePreview('GRADLE_METADATA')
use gradle 4.7 (newer version are incompatible with the meta data of the current coroutines library, they require something with 0.4 version and the current published one uses 0.3)
In the iOS module :
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core-native:0.23.4-native-1"
In your common module :
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.23.4"
If you have a js module, it may fail due to the gradle metadata feature. You can fix it by adding this before each of your "repositories" blocks (https://github.com/srs/gradle-node-plugin/issues/301)
repositories.whenObjectAdded {
if (it instanceof IvyArtifactRepository) {
metadataSources {
artifact()
}
}
}
Hope this will be enough !