Custom gradle script plugin written in kotlin dsl causing error - eclipse

I am trying to setup a multi-project setup with gradle and trying to generate eclipse projects with eclipse IDE plugin.
Below is my structure.
rootDir/
|---buildSrc/
|---src/
|---main/
|---gradle/
|---eclipse.gradle.kts
|---build.gradle.kts
|---app/
|---build.gradle.kts
|---models/
|---build.gradle.kts
|---services/
|---build.gradle.kts
|---build.gradle.kts
|---settings.gradle.kts
Below are the contents of specific files, e.g. settings.gradle.kts and build.gradle.kts
settings.gradle.kts
rootProject.name = "platform"
include("app", "models", "services")
rootDir/build.gradle.kts
...
val buildSrc by extra("$rootDir/buildSrc")
configure(subprojects) {
apply(from = "$buildSrc/src/main/gradle/eclipse.gradle.kts")
}
rootDir/buildSrc/src/main/gradle/eclipse.gradle.kts
plugins {
eclipse
}
eclipse {
project {
println("Running inside eclipse closure for $name")
}
}
When I run ./gradlew I am getting below error:
Expression 'eclipse' cannot be invoked as a function. The function 'invoke()' is not found
FAILURE: Build failed with an exception.
* Where:
Script 'D:\work\sources\repos\platform\buildSrc\src\main\gradle\eclipse.gradle.kts' line: 5
* What went wrong:
Script compilation errors:
Line 5: eclipse {
^ Expression 'eclipse' cannot be invoked as a function. The function 'invoke()' is not found
Line 5: eclipse {
^ Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public val PluginDependenciesSpec.eclipse: PluginDependencySpec defined in org.gradle.kotlin.dsl
Line 6: project {
^ Type mismatch: inferred type is () -> Unit but String! was expected
3 errors
However, when I do below changes, it works without errors
rootDir/buildSrc/src/main/gradle/eclipse.gradle replace eclipse.gradle.kts file with eclipse.gradle and make changes as per groovy DSL
apply plugin: 'eclipse'
eclipse {
project {
println("Running inside eclipse closure for $name")
}
}
refer correct file in rootDir/build.gradle.kts
...
val buildSrc by extra("$rootDir/buildSrc")
configure(subprojects) {
apply(from = "$buildSrc/src/main/gradle/eclipse.gradle")
}
Is having a kotlin file in gradle directory in rootDir/buildSrc/src/main/gradle (the custom script plugin) causing this issue? If so, is there any way to write a custom script plugin - not binary plugin - in kotlin dsl?
I have tried putting kotlin script in rootDir/buildSrc/src/main/kotlin/eclipse.gradle.kts but this does not helps.
Any help would be appreciable.

Related

Gradle DSL - Eclipse Equivalent for IDEA Module Property

Good localtime,
I am in the process of updating legacy (4.8.1) Gradle build files for a big-McLarge-huge, multimodule project. We utilize an intellij.gradle file which has the following line (marked by comment):
idea {
module {
inheritOutputDirs = true // <-- HOW DO I DO THIS
downloadJavadoc = true
downloadSources = true
}
workspace.iws.withXml { provider ->
def node = provider.asNode()
def dynamicClasspath = node.component.find { it."#name" == "dynamic.classpath" }
if (dynamicClasspath != null) {
dynamicClasspath."#value" = "true"
}
}
From the 4.8.1 DSL docs:
If true, output directories for this module will be located below the
output directory for the project; otherwise, they will be set to the
directories specified by IdeaModule.getOutputDir() and
IdeaModule.getTestOutputDir().
Any ideas on what the Eclipse DSL equivalent of inheritOutputDirs? Should this be handled using the eclipseClasspath API? Right now everything is building fine, but the Eclipse Java builder is is flagging things.
References:
https://docs.gradle.org/4.8.1/dsl/org.gradle.plugins.ide.idea.model.IdeaModule.html
https://docs.gradle.org/4.8.1/dsl/org.gradle.plugins.ide.eclipse.model.EclipseClasspath.html
Usually this would have been picked up through sourceSets but I can't see what your project looks like...
If your subproject uses Gradle to generate sources into /build/cxf/generated-sources directory, then you can tell Eclipse via Gradle DSL to include that as a source folder like this:
plugins { id 'eclipse' }
eclipse.classpath.file.whenMerged {
// this is the brute-force approach; there is likely a better way to add a source folder
entries << new org.gradle.plugins.ide.eclipse.model.SourceFolder('build/cxf/generated-sources', null)
}
Once this is run (via gradle eclipseClasspath) you should see a build/cxf/generated-sources folder under your project node in the Package Explorer or Project Explorer. Sort of like this:
NOTE: This is untested because I don not have a sample project to work with.
There is more discussion here: How to add gradle generated source folder to Eclipse project?

Intellij gradle sync error: scala import error

I have updated my IntelliJ and the gradle sync outputs a warning which affects my IDE autocomplete.
I have tried looking for this problem and I've tried some fixes with package versions or change from compile to implementation, but none have worked.
Here is my gradle part that seems to generate the error.
allprojects {
apply plugin: 'java'
apply plugin: 'scala'
group = 'com.adobe.platform.activation'
sourceCompatibility = 1.8
// Once we migrate to our own jenkins, this will be removed
String gitBranch = System.getenv("GIT_BRANCH")
if (gitBranch != null && gitBranch != "master") {
String version = version.toString()
int dashIndex = version.lastIndexOf('-')
String prefix = version.substring(0, dashIndex)
String suffix = version.substring(dashIndex + 1)
String newVersion = "$prefix-$gitBranch-$suffix"
.replace("/", "-")
.replace("_", "-")
setVersion(newVersion)
}
}
The warning looks like this.
Warning:<i><b>root project '....': Unable to build Scala project configuration</b>
Details: org.gradle.api.GradleException: Cannot infer Scala class path because no Scala library Jar was found. Does root project '...' declare dependency to scala-library? Searched classpath: file collection.</i>
Apparently, replacing allprojects with subprojects seems to fix the problem.
Somehow, the project wanted to set the scala library for the root of the project, which contains no code.

Gradle init project for Scala application

I want to create a skeleton console app for Scala i.e. a single entry class with a main function that prints "Hello world".
I was able to create a Scala library init project by executing:
gradle init --type scala-library
however there seems to be no scala-application, running:
gradle init --type scala-application
The requested build setup type 'scala-application' is not supported. Supported types: 'basic', 'groovy-application', 'groovy-library', 'java-application', 'java-library', 'pom', 'scala-library'.
Is there no Scala console app template for Gradle?
No, there is no scala application template, however it is easy to make your generated "scala-library" project into a scala application in two steps:
Create your main class and method under a package under src/main/scala
Add two lines to your gradle.build, to add the 'application' plugin and specify your main class.
For example, you add src/main/scala/com/example/myapp/Main.scala:
package com.example.myapp
object Main {
def main(args: Array[String]): Unit = {
println("Hello")
}
}
Then to your gradle.build you add:
apply plugin: 'application'
mainClassName='com.example.myapp.Main'
On top of what you have for Java you pretty much only need to add apply plugin: 'scala' and change Main to be:
object Main extends App {
println('Hello, World!')
}
I ended up doing just that.
Additionally, if you want joint compilation (and have compiler understand Java and Scala in the same place) you can add the below snippet (one block per source set: main, test, jmh, etc.):
sourceSets.main {
java.srcDirs = []
scala.srcDirs = ['src/main/scala', 'src/main/java']
scala.include '**/*.*'
}
sourceSets.test {
java.srcDirs = []
scala.srcDirs = ['src/test/scala', 'src/test/java']
scala.include '**/*.*'
}
As of Gradle 6.7 the scala-application build type exists now.

Kotlin setup via gradle on eclipse

Struggling to get Kotlin running on eclipse.
I've started new graddle project. Added dependencies as prescribed on kotlin's site.
Build passes without errors.
I've created 'main.kt' file under src/java/main with:
fun main(args: Array<String>) {
println("foo")
}
BUT, I have two problems:
1. anything from kotlin e.g. println highlighted as 'unresolved reference'.
2. I can't run a program - Error: Could not find or load main class MainKt (rightclick on main.kr run as 'kotlin application')
If I create 'new kotlin project' everything works.
my graddle build script:
plugins {
id "org.jetbrains.kotlin.jvm" version "1.1.2-2"
}
repositories {
jcenter()
mavenCentral()
}
dependencies {
//api 'org.apache.commons:commons-math3:3.6.1'
implementation 'com.google.guava:guava:21.0'
testImplementation 'junit:junit:4.12'
compile "org.jetbrains.kotlin:kotlin-stdlib:1.1.2-2"
compile "org.jetbrains.kotlin:kotlin-stdlib-jre8"
compile "org.jetbrains.kotlin:kotlin-reflect"
testCompile "org.jetbrains.kotlin:kotlin-test"
testCompile "org.jetbrains.kotlin:kotlin-test-junit"
}
sourceSets {
main.java.srcDirs = ['src/main/java']
main.kotlin.srcDirs = ['src/main/java', 'src/main/kotlin']
main.resources.srcDirs = ['src/main/resources']
}
What did I do wrong?
I've zero Java knowledge if that helps, so probably I've made some trivial error.
UPDATE:
Installed a Spring plugin and generated a new web app via it including gradle.
But Kotlin behaves unpredictably there too.
At first I was not able to run it as run as Kotlin application and it errored with main could not be found, BUT sometimes it run and crashed immediately. It started to launch and crash after I've deleted and edited classes, tried creating it under other package, removing and adding Kotlin (I can't reproduce sequence to make it work again).
Fun part that gradle boot build launches everything and all works it somehow finds Kotlin's main.
Probably some issue with Kotlin plugin itself (it's load probably depends on certain events that doesn't always fire)
Add the following to your configuration:
apply plugin: 'eclipse'
eclipse {
classpath {
containers 'org.jetbrains.kotlin.core.KOTLIN_CONTAINER'
}
}
See https://gitlab.com/frnck/kotlin-gradle-eclipse for a working configuration.
I'd like to add to frnck answer that this is only part of the solution. I also had to add these lines:
eclipse.project {
buildCommand 'org.jetbrains.kotlin.ui.kotlinBuilder'
natures 'org.jetbrains.kotlin.core.kotlinNature'
natures 'org.eclipse.jdt.core.javanature'
linkedResource name: 'kotlin_bin', type: '2', locationUri: 'org.jetbrains.kotlin.core.filesystem:/aio/kotlin_bin'
}
For Eclipse 2018-12 and kotlin 1.3 the solution was a combination of other answers plus some additional settings file:
eclipse {
classpath {
//Adds the kotlin container to the classpath
containers 'org.jetbrains.kotlin.core.KOTLIN_CONTAINER'
//Fixes the right output path
defaultOutputDir = file('bin')
//Make all src folders output in the same output folder (default)
file {
whenMerged {
// use default Output for all source-folders. see also defaultOutputDir per project
entries.each { source ->
// only Source-folders in the project starting with '/' are project-references
if (source.kind == 'src' && !source.path.startsWith('/')) {
source.output = null
}
}
}
}
}
project{
buildCommand 'org.jetbrains.kotlin.ui.kotlinBuilder'
//Fixes the natures
natures 'org.jetbrains.kotlin.core.kotlinNature'
natures 'org.eclipse.jdt.core.javanature'
//Links the kotlin_bin folder (generated class files)
linkedResource name: 'kotlin_bin', type: '2', locationUri: "org.jetbrains.kotlin.core.filesystem:/${project.name}/kotlin_bin".toString()
file{
whenMerged{
def kotlinPrefs = file('.settings/org.jetbrains.kotlin.core.prefs')
def jdkHome = System.properties.'java.home'
if(!(jdkHome)){
throw new GradleException('No JDK home available for setting up Eclipse Kotlin plugin, setup env "java.home" or update this script.')
}
kotlinPrefs.write """\
codeStyle/codeStyleId=KOTLIN_OFFICIAL
codeStyle/globalsOverridden=true
compilerPlugins/jpa/active=true
compilerPlugins/no-arg/active=true
compilerPlugins/spring/active=true
eclipse.preferences.version=1
globalsOverridden=true
jdkHome=$jdkHome
""".stripIndent()
}
}
}
}
I would like to add to Felipe Nascimento's answer that the location of the .settings folder does not yet exist. It works when the line below is inserted into that answer.
def kotlinPrefs = file("../${project.name}/.settings/org.jetbrains.kotlin.core.prefs".toString())
I have found that the JAVA_HOME environment variable that is set when your run this task ;
gradle cleanEclipse eclipse
is the one that is included in the Eclipse BuildPath

Gradle Api Sources and Doc when writing Gradle Plugins

The question:
How do I get the sources and javadoc/groovydoc for the gradle-api code integrated into an Eclipse project?
Background:
I'm using Gradle to build a Gradle-plugin that I'm writing. I'm using Eclipse as an IDE for this project and my Gradle script for building this plugin is using the 'Eclipse' plugin to generate my Eclipse project. Also, I'm using Spring's Gradle plugin for Eclipse which grabs all my dependencies from my build.gradle file.
The dependencies block for this Gradle script has
dependencies {
compile localGroovy()
compile gradleApi()
// I want something like: 'compile gradleApiSources()' here
// I want something like: 'compile gradleApiDoc()' here as well
}
Justification:
As I'm learning to write Gradle plugins, it would be helpful to be able to see the documentation and even implementation for Gradle to help me learn what I'm doing.
This works for me in Eclipse:
plugins.withType(EclipsePlugin) {
plugins.withType(JavaBasePlugin) {
eclipse {
classpath {
file {
whenMerged { classpath ->
String gradleHome = gradle.getGradleHomeDir()
.absolutePath
.replace(File.separator, '/')
String gradleSourceDirectory = "${gradleHome}/src"
classpath.entries.each { entry ->
if (entry in org.gradle.plugins.ide.eclipse.model.AbstractLibrary
&& entry.library.path.contains('generated-gradle-jars')) {
entry.sourcePath =
new org.gradle.plugins.ide.eclipse.model.internal.FileReferenceFactory()
.fromPath(gradleSourceDirectory)
}
}
}
}
}
}
}
}
Make sure that your Gradle Home contains the source directory. If you use the wrapper this can be done by updating the distributionUrl to an -all version in the wrapper task.
You will also need to stop the Gradle daemons that are running otherwise they will keep their own "home": ./gradlew --stop, then you can go ahead and run the task: ./gradlew eclipse
See GRADLE-2133 (which this answer was adapted from)
I don't have an answer for eclipse but I can tell you how I do this for intellij which might give you some inspiration. It would be nice if this were available more easily.
private void addGradleSourceDeps() {
PathFactory pf = new PathFactory()
pf.addPathVariable('GRADLE_HOME', project.gradle.gradleHomeDir)
project.extensions.idea.module.iml.whenMerged { Module module ->
module.dependencies.grep {
it instanceof ModuleLibrary && ((ModuleLibrary) it).classes.grep { Path path ->
path.relPath.substring(path.relPath.lastIndexOf('/') + 1).startsWith('gradle-')
}
}.each { ModuleLibrary lib ->
// TODO this needs to be fixed for gradle 1.9 which now includes separate sub directory for each jar
// for now a workaround is to execute the following
// cd $GRADLE_HOME
// for each in $(find . -mindepth 2 -maxdepth 2 -type d ! -name META\-INF); do cp -a ${each} .;done
lib.sources.add(pf.path('file://$GRADLE_HOME$/src'))
}
module.dependencies.grep {
it instanceof ModuleLibrary && ((ModuleLibrary) it).classes.grep { Path path ->
path.relPath.substring(path.relPath.lastIndexOf('/') + 1).startsWith('groovy-all')
}
}.each { ModuleLibrary lib -> lib.sources.add(pf.path('file://$GROOVY_SRC_HOME$')) }
}
}
This relies on me having installed a gradle src distribution into a location available via the GRADLE_HOME path variable in intellij (and similar for GROOVY_SRC_HOME). You can also see my plugin currently uses gradle 1.8, the src layout changed in 1.9 so I need to fix this when I upgrade.