gradle configure plugin default during execution phase - plugins

I am new to gradle. I am trying to use a plugin but I want to change the default values of a plugin during execution
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.netflix.nebula:gradle-ospackage-plugin:2.0.3'
}
}
apply plugin: 'os-package-base'
Setting plugin defaults:
def version_local = version //project.version
ospackage {
version = version_local
.......
.......
}
I am using another plugin(gradle-release) which changes the version of an artifact and the value of it is present in project.version. The tasks of this release plugin executes before the buildRpm task of this plugin(ospackage)
I want to use the value of the version present in project.version during execution. But looks like the value is being set prior to execution of any tasks. Any ideas how?

This piece of code seems to do it.
buildRpm.doFirst {
version = project.version
}
Explanation: doFirst is an action which only gets run during execution phase of gradle, right before running buildRpm.

Related

Gatling performance test with Scala and Gradle

I am new to Gatling and Scala , I am trying to run the Gatling test example specified in the beginning parts of this video: https://www.youtube.com/watch?v=To7LJiK87Us, but using Gradle wrapper.
I created a gradle project in IntelliJ idea and the build.gradle file is below
buildscript {
repositories {
maven {
url '<url>'
credentials {
<><>
}
}
}
dependencies {
classpath "gradle.plugin.io.gatling.gradle:gatling-gradle-plugin:3.8.4"
}
}
apply plugin: "io.gatling.gradle"
apply plugin: 'scala'
repositories {
maven {
url '<>'
credentials {
<><>
}
}
mavenCentral()
}
dependencies {
implementation 'org.scala-lang:scala-library:2.12.4'
gatling 'org.scala-lang:scala-library:2.12.4'
gatling 'au.com.bytecode:opencsv:2.4'
gatling group: 'org.scalaj', name: 'scalaj-http_2.12', version: '2.3.0'
gatling group: 'org.json4s', name: 'json4s-native_2.12', version: '3.5.3'
}
compileGatlingScala {
scalaCompileOptions.additionalParameters = ["-feature"]
}
gatling {
simulations = {
// Enable ALL perf testing, regardless of current pass/fail state
include "**/simulation/*Simulation*.scala"
}
}
sourceSets.gatling.resources.srcDir('conf')
gatling {
logLevel = 'WARN' // logback root level
logHttp = 'ALL'
}
Note: I have a few extra dependencies here like 'opencsv' that I will be needing later for the actual performance testing.
And my LoadSimulation script is as below
class LoadSimulation extends Simulation {
val scn = scenario("JSON")
.exec(
http("GET")
.get("http://jsonplaceholder.typicode.com/comments")
)
setUp(
scn.inject(atOnceUsers(1))
)
}
When I try to run the performance test using gradlew, it says "build successful', but I don't see a result in the reports folder under /build
>gradlew gatlingRun-LoadSimulation
BUILD SUCCESSFUL in 1s
3 actionable tasks: 1 executed, 2 up-to-date
Could anyone please tell me what I am doing wrong? Is this not how I should be running it?
EDIT
Updated to below dependencies as per answers below, still the same result, nothing in the /build/reports/gatling folder.
dependencies {
implementation 'org.scala-lang:scala-library:2.13'
gatling 'org.scala-lang:scala-library:2.13'
gatling 'au.com.bytecode:opencsv:2.4'
gatling group: 'org.scalaj', name: 'scalaj-http_2.13', version: '2.4.2'
gatling group: 'org.json4s', name: 'json4s-native_2.13', version: '3.6.7'
}
There's something very wrong: you're enforcing Scala 2.12 and Scala 2.12 based libraries while using Gatling 3.8 that requires Scala 2.13.
Please have a look at the official sample project: https://github.com/gatling/gatling-gradle-plugin-demo-scala/blob/main/build.gradle
In scala language the minor versions are actually major versions. You can expect a lot of differences between 2.12 and 2.13. Thats the problem you are facing.
Its like comparing Java 7 and Java 8.
I had the same confusion back in the days with the way Scala versions work.

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?

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

1 Eclipse project, 2 artifacts with Gradle

I want to create structure for my new project and I intend to build it with Gradle. I already know that if I place sources and tests in one project plugins like MoreUnit will handle it easily and create tests for my classes right where I want them.
However it creates some awkward dependency issues when my project consists of several subprojects depending on each other - to be precise when I want to use some common code in tests in project A and then reuse it in tests in project B I had to do some workarounds like
project(':B') {
// ...
dependencies {
// ...
if (noEclipseTask) {
testCompile project(':A').sourceSets.test.output
}
}
}
sometimes there were also some evaluation problem so another hack had to be introduced:
project(':B') {
evaluationDependsOn(':A')
}
Splitting this into 2 separate projects got rid of that issue but then MoreUnit no longer was able to trace where it should create new test files, and mark which methods have been tested. I haven't found anything in MoreUnit config that would allow me to fix that, so am trying to fix this from Gradle side.
Can we arrange things so I can have several subprojects, sources and tests are arranged in maven like manner (project/src/java, project/test/java) but tests and sources will create separate artifacts? If I am solving the wrong problem then how should I solve the right one?
You can create some testenv jar for common like:
sourceSets {
testenv {
compileClasspath += main.output
runtimeClasspath += main.output
}
}
configurations {
testenvCompile {
extendsFrom runtime
}
testCompile {
extendsFrom testenvRuntime
}
testenvDefault {
extendsFrom testenvRuntime
}
}
and
task testenvJar(type: Jar, group: 'build', description: 'Assembles a jar archive containing the testenv classes.') {
from sourceSets.testenv.output
appendix = 'testenv'
// add artifacts to testenvRuntime as task 'jar' does automatically (see JavaPlugin#configureArchivesAndComponent:106 and http://www.gradle.org/docs/current/userguide/java_plugin.html, "Figure 23.2. Java plugin - dependency configurations")
configurations.testenvRuntime.artifacts.add new org.gradle.api.internal.artifacts.publish.ArchivePublishArtifact(testenvJar)
}
task testenvSourcesJar(type: Jar, group: 'build', description: 'Assembles a jar archive containing all testenv sources.') {
from sourceSets.testenv.allSource
appendix = 'testenv'
classifier = 'sources'
}
artifacts {
archives testenvJar
archives testenvSourcesJar
}
and use it in your depended projects like
testCompile project(path: ':common', configuration: 'testenvDefault')
I hope this helps!

Gradle plugin project version number

I have a gradle plugin that uses the project.version variable.
How ever, the version in the plugin does not update when I change the version in the build.gradle file.
To illustrate:
plugin
// my-plugin
void apply(Project project) {
project.tasks.create(name: 'printVersionFromPlugin') {
println project.version
}
}
build.gradle
version '1.0.1' // used to be 1.0.0
task printVersion {
println project.version
}
apply plugin: 'my-plugin'
Result
> gradle printVersion
1.0.1
> gradle printVersionFromPlugin
1.0.0
You can use gradle properties to extract project version without adding a dedicated task to the build.gradle file.
For example:
gradle properties -q | grep "version:" | awk '{print $2}'
Both the build script and the plugin make the same mistake. They print the version as part of configuring the task, rather than giving the task a behavior (task action). If the plugin is applied before the version is set in the build script (which is normally the case), it will print the previous value of the version property (perhaps one is set in gradle.properties).
Correct task declaration:
task printVersion {
// any code that goes here is part of configuring the task
// this code will always get run, even if the task is not executed
doLast { // add a task action
// any code that goes here is part of executing the task
// this code will only get run if and when the task gets executed
println project.version
}
}
Same for the plugin's task.