I got an error using this build.grafle file and don't know how to fix it - gradle

Here's the Error:
FAILURE: Build failed with an exception.
Where: Build file '/home/wieland/GitGradlePackaging/build.gradle' line: 22
What went wrong: A problem occurred evaluating root project 'GitGradlePackaging'.
Could not get unknown property 'org' for object of type org.gradle.api.internal.initialization.DefaultScriptHandler.
And Here's my build.gradle File:
/*
* This file was generated by the Gradle 'init' task.
*
* This generated file contains a sample Java project to get you started.
* For more details take a look at the Java Quickstart chapter in the Gradle
* user guide available at https://docs.gradle.org/4.6/userguide/tutorial_java_projects.html
*/
//From example: http://mrhaki.blogspot.co.at/2015/04/gradle-goodness-use-git-commit-id-in.html
buildscript {
repositories {
jcenter()
}
dependencies {
//Add dependencies for build script, so we can access Git from our build script
classpath 'org.ajoberstar:grgit:1.1.0'
}
def git = org.ajoberstar.grgit.Grgit.open(file('.'))
//To save Githash
def githash = git.head().abbreviatedId
}
plugins {
// Apply the java plugin to add support for Java
id 'java'
// Apply the application plugin to add support for building an application
id 'application'
// Apply the groovy plugin to also add support for Groovy (needed for Spock)
id 'groovy'
id 'distribution'
}
// Set version
project.version = mainProjectVersion + " - " + githash
project.ext.set("wholeVersion", "$project.version - $githash")
project.ext.set("buildtimestamp", "2000-01-01 00:00")
def versionfilename = "versioninfo.txt"
def GROUP_DEBUG = 'Debug'
// Task to print project infos
task debugInitialSettings {
group = GROUP_DEBUG
doLast {
println 'Version: ' + project.wholeVersion
println 'Timestamp: ' + project.buildtimestamp
println 'Filename: ' + project.name
}
}
// To add the githash to zip
task renameZip {
doLast {
new File ("$buildDir/distributions/$project.name-${project.version}.zip")
.renameTo ("$buildDir/distributions/$project.name-${project.wholeVersion}.zip")
}
}
distZip.finalizedBy renameZip
// To add the githash to tar
task renameTar{
doLast {
new File ("$buildDir/distributions/$project.name-${project.version}.tar")
.renameTo ("$buildDir/distributions/$project.name-${project.wholeVersion}.tar")
}
}
distTar.finalizedBy renameTar
// Define the main class for the application
mainClassName = 'App'
dependencies {
// This dependency is found on compile classpath of this component and consumers.
compile 'com.google.guava:guava:23.0'
// Use the latest Groovy version for Spock testing
testCompile 'org.codehaus.groovy:groovy-all:2.4.13'
// Use the awesome Spock testing and specification framework even with Java
testCompile 'org.spockframework:spock-core:1.0-groovy-2.4'
testCompile 'junit:junit:4.12'
}
// In this section you declare where to find the dependencies of your project
repositories {
// Use jcenter for resolving your dependencies.
// You can declare any Maven/Ivy/file repository here.
jcenter()
}
//To generate Testreports as HTML
test {
reports {
junitXml.enabled = false
html.enabled = true
}
}
distributions {
main {
contents {
from { 'build/docs' }
into ('reports') {
from 'build/reports'
}
}
}
}
//To make sure that test and javadoc ran before zip and tar
distTar.dependsOn test
distZip.dependsOn test
distTar.dependsOn javadoc
distZip.dependsOn javadoc
Please keep in mind I have not much knowledge about gradle as I'm just starting to learn it!
Thanks in advance :)

You have to move the githash definition outside the buildscript block
buildscript {
repositories {
jcenter()
}
dependencies {
//Add dependencies for build script, so we can access Git from our build script
classpath 'org.ajoberstar:grgit:1.1.0'
}
}
def git = org.ajoberstar.grgit.Grgit.open(file('.'))
//To save Githash
def githash = git.head().abbreviatedId
The reason is that when the buildscript block is evaluated line by line, its dependencies are not yet loaded. When the rest of the script is evaluated, the dependencies of the buildscript block have already been loaded. This is actually the reason for the buildscript block existence: to be run before the rest of the build and prepare the setup.

Related

Multiple Gradle Files in the same project using apply from

I'm trying to segregate the gradle tasks to respective gradle files.
build.gradle
plugins {
id 'org.openapi.generator' version '4.3.1'
}
apply from: "$projectDir/gradle/script/openapi.gradle"
openapi.gradle
task buildSampleClient(type: org.openapitools.generator.gradle.plugin.tasks.GenerateTask) {
generatorName = "spring"
inputSpec = "$rootDir/src/main/resources/sample.yaml".toString()
outputDir = "$buildDir/generated".toString()
modelPackage = "com.sample"
}
When gradle build is run, getting this error
A problem occurred evaluating script.
Could not get unknown property 'org' for root project 'sample' of type org.gradle.api.Project.
But If I move the content of openapi.gradle into build.gradle it works fine.
Not sure what is the issue, could anyone help here please?
You should add plugin dependencies before your task definition to your openapi.gradle:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath "org.openapitools:openapi-generator-gradle-plugin:${openapiPluginDependencyVersion}"
}
}
apply plugin: "org.openapi.generator"
// your task goes here
task buildSampleClient(type: org.openapitools.generator.gradle.plugin.tasks.GenerateTask) {
...
}
gradle.properties:
openapiPluginDependencyVersion=4.3.0

Gradle Liquibase Integration

I am trying to integrate Liquibase in my project using Gradle.
For that I made below changes to build.gradle but it gives me error as follows:
Below is my build.gradle file:
buildscript {
repositories {
mavenCentral()
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath "org.liquibase:liquibase-gradle-plugin:2.0.1"
}
}
allprojects {'
apply plugin: 'liquibase'
}
dependencies {
liquibaseRuntime 'org.liquibase:liquibase-core:3.6.1'
liquibaseRuntime 'org.liquibase:liquibase-groovy-dsl:2.0.1'
liquibaseRuntime 'mysql:mysql-connector-java:5.1.34'
}
liquibase {
activities {
doFirst {
if (!project.hasProperty('runList')) {
project.ext.runList = "main,test"
}
}
main {
defaultsFile "$projectDir/sql-migration/mysql/app_mysql.properties"
logFile "$projectDir/sql-migration/mysql/logs/liquibase-" + new Date().format("yyyy-MM-dd_HH-mm-ss")+".log"
}
test {
defaultsFile "$projectDir/sql-migration/mysql/app_test_mysql.properties"
logFile "$projectDir/sql-migration/logs/liquibase-test-" + new Date().format("yyyy-MM-dd_HH-mm-ss")+".log"
}
}
// To execute liquibase on single environment, gradlew app:update -PrunList=test
runList = project.ext.runList
}
I am not able to get why it is not able to find out 'liquibaseRuntime' repositories.
Any help in this would be really appreciated.
Assuming that you have a changelog file, make sure that the changelog file is properly referenced from build.gradle.
Also I would suggest defining the liquibase.url, username and password.
Refer to this post for detailed implementation:
https://dzone.com/articles/managing-your-database-with-liquibase-and-gradle
The error message
Cannot resolve external dependency [...] because no repositories are defined
indicates that you're missing a repositories block. You have one in your buildscript, but you probably need to move it to the top-level, as shown here.

Trying to add Applied Energistics api through build.gradle

I am starting on a minecraft mod, but I cannot get the build.gradle right.
I wanted to create a mod on top of applied energistics but I cannot get it to build when I add this mod as a gradle dependency. I looked all the dependencies up on an other repository, but when I build it gives errors like below, and some other errors on the general minecraft code base
Error:(3, 26) java: package net.minecraft.init does not exist
This is the code I have right now:
buildscript {
repositories {
jcenter()
maven { url = "http://files.minecraftforge.net/maven" }
}
dependencies {
classpath 'net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT'
}
}
apply plugin: 'net.minecraftforge.gradle.forge'
//Only edit below this line, the above code adds and enables the necessary things for Forge to be setup.
version = mod_version + "-" + mod_channel
group = mod_group
archivesBaseName = mod_basename
sourceCompatibility = targetCompatibility = '1.8' // Need this here so eclipse task generates correctly.
compileJava {
sourceCompatibility = targetCompatibility = '1.8'
}
minecraft {
version = minecraft_version + "-" + forge_version
replaceIn "package-info.java"
replace "#version#", project.version
replace "#modversion#", mod_version
replace "#modchannel#", mod_channel
// used when launching minecraft in dev env
mappings = mcp_mappings
}
repositories {
maven {
name 'Mobius Repo'
url "http://mobiusstrip.eu/maven"
}
maven {
name = "JEI repo"
url "http://dvs1.progwml6.com/files/maven"
}
}
dependencies {
// installable runtime dependencies
compileOnly "mcp.mobius.waila:Hwyla:${hwyla_version}"
// compile against provided APIs
compileOnly "mezz.jei:jei_${minecraft_version}:${jei_version}:api"
compileOnly "mcp.mobius.waila:Hwyla:${hwyla_version}"
// at runtime, use the full JEI jar
runtime "mezz.jei:jei_${minecraft_version}:${jei_version}"
deobfCompile "appeng:appliedenergistics2:${ae_verion}"
}
processResources {
// this will ensure that this task is redone when the versions change.
inputs.property "version", project.version
inputs.property "mcversion", project.minecraft.version
// replace stuff in mcmod.info, nothing else
from(sourceSets.main.resources.srcDirs) {
include 'mcmod.info'
// replace version and mcversion
expand 'version':project.version, 'mcversion':project.minecraft.version
}
// copy everything else except the mcmod.info
from(sourceSets.main.resources.srcDirs) {
exclude 'mcmod.info'
}
}
The version that I am trying to add is:
ae_verion=rv5-stable-8
You need to add 'api' at the end of the compile argument (used to be 'dev'). Also, iirc adding transitive=false solves dependency issues.
dependencies {
compile ("appeng:appliedenergistics2:${ae_version}:api") {
transitive = false
}
}

Gradle: How to set version from custom plugin

I've written a custom plugin (my first) which manages a "build number" which I want to include in the build.gradle "version" as so:
allprojects {
version = "1.2.3.${buildNumber}"
}
Unfortunately my plugin is never run and thus the buildNumber returned is "null".
Below is my build.gradle.
If I run "gradle showbuild" I see the right buildNumber.
If I run "gradle showInfo" the build number reported is "null".
Somehow I need to get gradle to call my plugin task 'buildInfoLoad' before the "version" value is set in allprojects. Since I'm knew to gradle I am struggling with this.
Any pointers would be most appreciated!
buildscript {
repositories {
maven {
// Access to MangoGrove
url uri('../repo')
}
maven { // aka "jcenter()"
url "https://jcenter.bintray.com"
}
}
dependencies {
// Provide the "provided" and "optional" methods for dependencies
classpath 'com.netflix.nebula:gradle-extra-configurations-plugin:3.0.3'
classpath group: 'org.mangogrove.gradle',
name: 'MangoGrove',
version: '1.0.0-SNAPSHOT'
}
}
apply plugin: 'org.mangogrove.gradle'
task showbuild(dependsOn: 'buildInfoLoad') << {
println("BI build number: $buildinfo.buildNumber")
println("BI build time: $buildinfo.buildTime")
}
task createbuild(dependsOn: 'buildInfoCreate') << {
println("BI build number: $buildinfo.buildNumber")
println("BI build time: $buildinfo.buildTime")
}
allprojects {
ext {
buildNumber = "$buildinfo.buildNumber"
}
version = "1.0.0.${buildNumber}-alpha2"
//version = "1.0.0.${buildinfo.buildNumber}-alpha2"
apply plugin: 'eclipse'
eclipse {
classpath {
downloadSources=true
//downloadJavadoc=true
}
}
}
task showInfo << {
println("Product Version is $version")
println("Product BuildNumber is $buildNumber")
}

avro gradle plugin sample usage

I am trying to use the avro-gradle-plugin on github, but have not gotten any luck getting it to work. Does anyone have any sample code on how they get it to work?
I figured out how to do it myself. The following is a snippet that I would like to share for people who might run into the same issues as I did:
apply plugin: 'java'
apply plugin: 'avro-gradle-plugin'
sourceCompatibility = "1.6"
targetCompatibility = "1.6"
buildscript {
repositories {
maven {
// your maven repo information here
}
}
dependencies {
classpath 'org.apache.maven:maven-artifact:2.2.1'
classpath 'org.apache.avro:avro-compiler:1.7.1'
classpath 'org.apache.avro.gradle:avro-gradle-plugin:1.7.1'
}
}
compileAvro.source = 'src/main/avro'
compileAvro.destinationDir = file("$buildDir/generated-sources/avro")
sourceSets {
main {
java {
srcDir compileAvro.destinationDir
}
}
}
dependencies {
compileAvro
}
I found "com.commercehub.gradle.plugin.avro" gradle plugin to work better.
use the folllowing:
// Gradle 2.1 and later
plugins {
id "com.commercehub.gradle.plugin.avro" version "VERSION"
}
// Earlier versions of Gradle
buildscript {
repositories {
jcenter()
}
dependencies {
classpath "com.commercehub.gradle.plugin:gradle-avro-plugin:VERSION"
}
}
apply plugin: "com.commercehub.gradle.plugin.avro"
more details at https://github.com/commercehub-oss/gradle-avro-plugin
When evaluating a plugin the following questions needs to be asked:
Are generated files included into source jar?
Is plugin fast? Good plugin use avro tools api instead of forking VM for every file. For large amount of files creating VM for every file can take 10min to compile.
Do you need intermediate avsc files?
Is build incremental (i.e. do not regenerate all files unless one of the sources changed)?
Is plugin flexible enough to give access to generated schema files, so further actions, such as registration schema in schema repository can be made?
It is easy enough to implement without any plugin if you are not happy with plugin or need more flexibility.
//
// define source and destination
//
def avdlFiles = fileTree('src/Schemas').include('**/*.avdl')
// Do NOT generate into $buildDir, because IntelliJ will ignore files in
// this location and will show errors in source code
def generatedJavaDir = "generated/avro/java"
sourceSets.main.java.srcDir generatedJavaDir
//
// Make avro-tools available to the build script
//
buildscript {
dependencies {
classpath group:'org.apache.avro', name:'avro-tools' ,version: avro_version
}
}
//
// Define task's input and output, compile idl to schema and schema to java
//
task buildAvroDtos(){
group = "build"
inputs.files avdlFiles
outputs.dir generatedJavaDir
doLast{
avdlFiles.each { avdlFile ->
def parser = new org.apache.avro.compiler.idl.Idl(avdlFile)
parser.CompilationUnit().getTypes().each { schema ->
def compiler = new org.apache.avro.compiler.specific.SpecificCompiler(schema)
compiler.compileToDestination(avdlFile, new File(generatedJavaDir))
}
}
}
}
//
// Publish source jar, including generated files
//
task sourceJar(type: Jar, dependsOn: buildAvroDtos) {
from sourceSets.main.allSource
// Package schemas into source jar
into("Schemas") { from avdlFiles }
}
// Clean "generated" folder upon "clean" task
clean {
delete('generated')
}
Configuration for avro with gradle as build tool need to add along with applying java plugin.
below changes in settings.gradle
pluginManagement {
repositories {
gradlePluginPortal()
mavenCentral()
}
}
below changes in build.gradle
plugins {
id "com.github.davidmc24.gradle.plugin.avro" version "1.3.0"
}
repositories {
mavenCentral()
}
dependencies {
implementation "org.apache.avro:avro:1.11.0"
}
generateAvroJava {
source("${projectDir}/src/main/resources/avro")//sourcepath avrofile
}
if you want to generate setter methods too add this task too in build.gradle
avro {
createSetters = true
}
link for reference

Resources