How to execute gradle task during project import in Intellij Idea - gradle

Let's assume my build.gradle file contains task generateSources which as name suggests generates additional java files. It's easy to ensure that generateSources is executed before compileJava: compileJava.dependsOn generateSources. How can I make sure generateSources is called when importing project into Intellij Idea as well?

To elaborate on #vladimir-sitnikov's answer: I added the idea-ext-plugin to my root project:
apply plugin: 'org.jetbrains.gradle.plugin.idea-ext'
// ...
buildscript {
dependencies {
classpath "org.jetbrains.gradle.plugin.idea-ext:org.jetbrains.gradle.plugin.idea-ext.gradle.plugin:0.7"
}
}
Because without that I wasn't able to use it in my sub project, but now it works like this:
idea.project.settings.taskTriggers {
beforeSync tasks.getByName("generateSources")
}
Adding the plugin to the sub-project only didn't do it.
Note: The plugin's documentation is kind of limited, but in "DSL spec v. 0.2" is stated
beforeSync - before each Gradle project sync. Will NOT be executed on initial import
Didn't try that, but it works with existing projects.

This can be done via id("org.jetbrains.gradle.plugin.idea-ext") plugin (https://github.com/JetBrains/gradle-idea-ext-plugin).
See sample code in Gradle sources: https://github.com/gradle/gradle/blob/135fb4751faf2736c231636e8a2a92d47706a3b9/buildSrc/subprojects/ide/src/main/kotlin/org/gradle/gradlebuild/ide/IdePlugin.kt#L147

You can set the task in Gradle tool window: Execute Before Sync:

Related

How to set the gradle outout folder for the kotlin2JS plugin?

I have a KotlinJs only project which I use official kotlin2js gradle to build, and no problems there.
How to setup the output folder, currently, the building of subproject will result in a build which locates inside the subproject folder, how to set it to somewhere else? I tried:
sourceSets {
main {
kotlin.outputDir = new File(‘./out/‘)
}
}
and
sourceSets {
main.kotlin.outputDir = new File(‘./out/’)
}
No luck.
What I want is to no matter how many subprojects are there, the output folder should be in some path like ./build/projectA and ./build/projectB, rather than all in their own folder. How to do this?
Currently, it's done through the task configuration, namely setting its kotlinOptions.outputFile:
compileKotlin2Js.kotlinOptions.outputFile = "out/output.js"
It's briefly mentioned in the tutorial: Getting Started with Kotlin and JavaScript with Gradle

Executing integration tests in gradle

Me and my team are working on a project with a lot of modules. We are using gradle for the project and everyone is new to gradle. We have a Main parent project i.e, parent build with the details of project dependencies. We want to add the integration_test task configuration to all the modules so that we can call the command gradle integration_test. So is there any way or concept of writing the configuration in the main module and make the child projects import the same configuration.
FYI: I tried it by directly adding it to the main project but got an error saying the classpath for the files which I specified does not exists. Any help or thought would be appreciated. Thanks in advance.
Is there a particular reason to split "integration tests" from the standard test task?
If so, you can run the same script for all subprojects from the main project's build file: https://docs.gradle.org/current/userguide/multi_project_builds.html#sec:subproject_configuration
For instance:
subprojects {
task integrationTest {
// whatever you need
}
}
I am note sure if this is what you talk about in the last paragraph. If so, please attache the error message you get.
It is also possible to "import" some configuration by subprojects, but the above definition is better in most scenarios.

Creating a post build copy task with Gradle

I am struggling with the Gradle build lifecycle; specifically with the split between the configuration and execution phases. I have read a number of sections in the Gradle manual and have seen a number of ideas online, but have not found a solution to the following problem:
I want to run a specific task to produce an artifact at the end of my java-library-distribution build that is a flattened version of the runtime configuration jars. That is, I only want to produce the artifact when I run the specific task to create the artifact.
I have created the following task:
task packageSamplerTask(type: Tar, dependsOn: distTar) {
description "Packages the build jars including dependencies as a flattened tar file. Artifact: ${distsDir}/${archivesBaseName}-${version}.tar"
from tarTree("${distsDir}/${archivesBaseName}-${version}.tar").files
classifier = 'dist'
into "${distsDir}/${archivesBaseName}-dist-${version}.tar"
}
Although this task does produce the required artifact, the task runs during gradle's configuration phase. This behavior has the following consequences:
Irrespective of which task I run from the command line, this packageSamplerTask task is always run, often unnecessarily; and
If I clean the project, then the build fails on the next run because $distsDir doesn't exist during the configuration phase (obviously).
It appears that if I extend the Copy task in this manner I'm always going to get this kind of premature behavior.
Is there a way to use the << closure / doLast declarations to get what I want? Or is there something else I'm missing / should be doing?
Update
After further work I have clarified my requirements, and resolved my question as follows (specifically):
"I want to package my code and my code's dependencies as a flat archive of jars that can be deployed as a jMeter plugin. The package can then be installed by unpacking into the jMeter lib/ext directory, as is. The package, therefore, must not include the jMeter jars (and their dependencies) which are used for building and testing"
Because Gradle doesn't appear to support the Maven-like provided dependency management, I created a new configuration for my package which excludes the jMeter jars.
configurations {
jmpackage {
extendsFrom runtime
exclude group: 'org.apache.jmeter', name: 'ApacheJMeter_core', version: '2.11'
exclude group: 'org.apache.jmeter', name: 'ApacheJMeter_java', version: '2.11'
}
}
And then created the following task (using the closure recommendation from Peter Niederwieser):
task packageSamplerTask(type: Tar, dependsOn: assemble) {
from { libsDir }
from { configurations.jmpackage.getAsFileTree() }
classifier = 'dist'
}
This solution appears to work, and it allows me to use just theGradle java plugin, too.
The task declaration is fine, but the flattening needs to be deferred too:
...
from { tarTree("${distsDir}/${archivesBaseName}-${version}.tar").files }
Also, the Tar file should be referred to in a more abstract way. For example:
from { tarTree(distTar.archivePath).files }
First your task isn't executed in the configuration phase but like EVERY task it is configured in that phase. And your closure is just a configuration of your task (a Configuration closure, not an Action closure). That is why your code is "executed" in the configuration phase".
If you want your code to be executed in the execution phase have to write it in a doLastclosure or doFirst. But in your case it is better to keep it in a configuration closure, because you are configuring your task.
To make sure your build doesn't fail because of the missing folder, you can create it with distsDir.mkdirs().

Gradle - Add additional task to existing task

I'm working on a project that uses EJB2s. The created EJB Jars require additional processing by the application server before they're bundled in the war/ear and deployed.
I have created a custom task that works to do the additional processing if I invoke it explicitly (gradle ejbDeploy), but am having trouble fitting it into the gradle multi-project lifecyle. I need to somehow add it to the build graph to execute automatically after the jar task.
My first attempt was to add it to jar with
jar.doLast{
ejbDeploy.execute()
}
which seems to work for arbitrary code blocks, but not for tasks
What's the recommended solution for this? I see three approaches:
Hook into the build graph and add it explicitly after the jar
task.
Set it up somehow in jar.doLast{}
Set it up as a prerequisite for the WAR task execution
Is there a recommended approach?
Thanks!
I would go for approach #3 and set it up as a dependency of the war task, e.g.:
war {
it.dependsOn ejbDeploy
...
}
I'm new to Gradle, but I would say the answer really depends on what you're trying to accomplish.
If you want to task to execute when someone runs the command gradle jar, then approach #3 won't be sufficient.
Here's what I did for something similar
classes {
doLast {
buildValdrConstraints.execute()
}
}
task buildValdrConstraints(type: JavaExec) {
main = 'com.github.valdr.cli.ValdrBeanValidation'
classpath = sourceSets.main.runtimeClasspath
args '-cf',valdrResourcePath + '/valdr-bean-validation.json'
}
Add the following, and then ejbDeploy will be executed right after jar, but before war
jar.finalizedBy ejbDeploy
See Gradle Docs. 18.11. Finalizer tasks

How to compile single class dependency in gradle outside the main project

I have a gradle project that contains only Selenium/TestNG test classes. They are executed against a deployed war application. All works fine and now I'm adding a java utility that will query the test base and print list of tests that belong to a given TestNG group. The utility should be compiled and executed separate from the main project, as users may want to query the test base before test execution.
I added the following to build.gradle:
task listgroups(dependsOn:'buildUtil' ) <<{
ant.java(classname: 'util.TestGroupScanner', fork: true,
classpath: "src/test/java")
}
task buildUtil {
compile {
source = "src/test/java/util"
}
}
However, when calling listgroups task, I'm getting the following error:
C:\console-bg1>g listgroups
FAILURE: Build failed with an exception.
(...)
* What went wrong:
A problem occurred evaluating root project 'console-bg1'.
> Could not find method compile() for arguments [build_4emu7duna2isgubc1k8uts8k9
8$_run_closure6_closure11#d210ab] on root project 'console-bg1'.
I'm not sure how to resolve this issue and needless to say, haven't found an answer online so far. Any pointers appreciated.
The problem is in the buildUtil task, as the error suggests. The buildUtil declares a compile closure, but such closure does not exist for the default task.
Let me try to clarify what your setup is. The util.TestGroupScanner source is in the src/test/java/util directory, which you want to compile separately from other source (presumably src/main/java and src/test/java). The buildUtil task is supposed to compile sources in src/test/java/util, and the listgroups task executes the scanner utility on sources src/test/java folder.
In this case, I'd suggest you declare a new source set for your utility sources, like this:
sourceSets {
util {
java {
srcDir 'src/test/java/util'
}
}
}
This will automatically create a compile task called compileUtilJava for you, that will compile those sources. I also think you'll want to include utility classes in the classpath when executing your tool, which can be retrieved by sourceSets.util.output.classesDir. So now your listgroups task will look like:
task listgroups(dependsOn: 'compileUtilJava' ) <<{
ant.java(classname: 'util.TestGroupScanner', fork: true,
classpath: "src/test/java:" + sourceSets.util.output.classesDir)
}
One thing I have noticed about your setup, is that src/test/java/util source folder is nested under src/test/java. Gradle will assume src/test/java to be the default folder for your project test, and will therefore automatically include it, and all of its children when running tests. Since you want to keep your utility folder separate from the default setup, I would recommend you put it in src/testutil/java, to avoid any clashes. If you do, don't forget to update the sourceSets setup above with the correct source path.
To solve this with gradle, I suggest to create a specific sourceset for your util class and add a task of type JavaExec that executes this class for printing your testng groups. Have a look at the following snippet:
apply plugin:'java'
...
...
configurations{
testUtilCompile.extendsFrom testCompile
}
...
...
sourceSets{
testUtil{
java {
srcDir "src/test/java"
include "util/**"
}
}
}
task printGroups(type:JavaExec){
main = "util.TestGroupScanner"
classpath = sourceSets.testUtil.runtimeClasspath
}
regards,
René

Resources