Build.gradle: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
No edit summary
Line 69: Line 69:
<syntaxhighlight lang='groovy'>
<syntaxhighlight lang='groovy'>
// This is a comment
// This is a comment
</syntaxhighlight>
=Variables=
There are two kinds of variables that can be declared in a build script: local variables and extra properties:
==Local Variables==
Local variables, which are a feature of the underlying Groovy language, are declared with the "def" keyword. They are only visible in the scope where they have been declared.
<syntaxhighlight lang='groovy'>
def myVariable = "something"
...
println myVariable
</syntaxhighlight>
==Extra Properties==
[[Gradle_Properties#Extra_Properties|Extra properties]] can be declared as follows:
<syntaxhighlight lang='groovy'>
...
ext {
    log4jVersion = "2.1.7"
    emailNotification = "build@example.com"
}
...
</syntaxhighlight>
</syntaxhighlight>



Revision as of 23:01, 19 May 2018

Overview

The project-level configuration script that contains task configuration for the current project, written in the Gradle's DSL. It tells Gradle what to build. The build script may contain any Groovy language element, including:

The property access and method calls are delegated to a project object.

build.gradle can be created automatically on project setup with gradle init. To make build scripts more concise, Gradle automatically adds the set of default Gradle import statements to the script.

build scripts are optional for multi-project builds.

build.gradle is written in Groovy. Groovy has both double-quoted and single-quoted String literals. The main difference is that double-quoted String literals support String interpolation.

Example

apply plugin: 'java'

group = "io.novaordis.playground.gradle"
version = "1.0"
sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
    mavenCentral()
}

configurations.all {
    resolutionStrategy.cacheChangingModulesFor 3600, 'seconds'
}

dependencies {
    implementation 'org.slf4j:slf4j-api:1.7.12'
    testImplementation 'junit:junit:4.+'
}

configurations {
    testImplementation.exclude group: 'com.example'
}

compileJava {
    options.compilerArgs += ['-Xlint']
}

javadoc {
    options.charSet = 'UTF-8'
}

task runMain(type: JavaExec) {
    classpath = sourceSets.main.runtimeClasspath
    main = "io.novaordis.playground.gradle.java.Main"
}

Non-Default Build File Name

The name of the build file can be changed using project descriptors:

project(':projectA').buildFileName = 'projectA.gradle'

Comments

// This is a comment

DSL

The following elements are part of Project API.

configurations.all

Applies enclosed to all configurations.

configurations.all {
    resolutionStrategy.cacheDynamicVersionsFor 10, 'minutes'
}

Alternative:

configurations.all {
    resolutionStrategy {
        cacheDynamicVersionsFor 10, 'minutes'
    }
}

Configuration

resolutionStrategy

https://docs.gradle.org/current/dsl/org.gradle.api.artifacts.ResolutionStrategy.html
cacheDynamicVersionsFor

Configures dynamic version caching threshold.

resolutionStrategy.cacheDynamicVersionsFor 10, 'minutes'
cacheChangingModulesFor

configurations

configurations {
    testCompile.exclude group: 'io.example'
}

buildscript

Used when external plugins need to be downloaded.

buildscript {
    repositories {
        maven { url 'https://plugins.gradle.org/m2/' }
    }
  dependencies {
    classpath 'com.netflix.nebula:gradle-ospackage-plugin:4.3.0'
  }
}

repositories

https://docs.gradle.org/current/userguide/declaring_repositories.html

Repositories are declared in a 'repositories' block:

repositories {
    ...
}

Multiple repositories can be declared in the same block. Syntax examples are available for custom Maven repositories, directory-based repositories, Maven Central, etc. The most common setting is declaring that our dependencies are available in Maven Central:

repositories {
    mavenCentral()
}

Multi-Project Configuration

allprojects

The allprojects block is used to add configuration items that will apply to all sub-projects, as well as the root project.

allprojects {
  repositories {
    ...
  }
}

"allprojects" is a property that contains a list with the current project and all its subprojects underneath it. It can be called with a closure, and the statements of the closure are delegated to the projects.

subprojects

The subprojects block is used to add configuration times for sub-projects only.

subprojects {
    ...
}

Custom Tasks

Custom Tasks

Respond to Build Lifecycle Events

Example of how to respond to project build lifecycle events.

allprojects {
      afterEvaluate { project ->
          if (project.hasTests) {
              println "Adding test task to $project"
              project.task('test') {
                   doLast {
                         println "running tests for $project"
                   }
              }
          }
     }
}
gradle.afterProject {project, projectState ->
      if (projectState.failure) {
          println "Evaluation of $project FAILED"
      } else {
          println "Evaluation of $project succeeded"
      }
}

Respond to Task Lifecycle Events

Examples of how to respond to task lifecycle events.

Task Creation

tasks.whenTaskAdded { task ->
      task.ext.srcDir = 'src/main/java'
}

Task Execution

gradle.taskGraph.beforeTask { Task task ->
      println "executing $task ..."
}
gradle.taskGraph.afterTask { Task task, TaskState state ->
      if (state.failure) {
          println "FAILED"
      }
      else {
          println "done"
      }
}