Build.gradle: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
(27 intermediate revisions by the same user not shown)
Line 1: Line 1:
=External=
=External=
* https://docs.gradle.org/current/userguide/writing_build_scripts.html
* https://docs.gradle.org/current/userguide/writing_build_scripts.html


=Internal=
=Internal=
 
* [[Gradle_Concepts#Configuration_Scripts_and_Core_Types|Gradle Concepts]]
* [[Gradle Configuration#build.gradle|Gradle Configuration]]
* [[Gradle Project#Overview|Project]]
* [[Gradle_Concepts#build.gradle|Gradle Concepts]]


=Overview=
=Overview=
 
build.gradle is referred to as an Gradle build script. It is the script interface to a [[Gradle_Project#Project_API_and_build.gradle_DSL|Project instance]].
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:
 
* <tt>println</tt>
* [[#Variables|variable declarations]]
* [[Gradle_Concepts#Plugin|plugin declarations]]
* [[#Repositories|repositories]]
 
The property access and method calls are delegated to a [[Gradle_Concepts#Project|project object]].
 
build.gradle can be created automatically on project setup with [[Gradle_Operations#Start_a_Project|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=
=Example=
<syntaxhighlight lang='groovy'>


<syntaxhighlight lang='groovy'>
apply plugin: 'java'
apply plugin: 'java'


group = "io.novaordis.playground.gradle"
// name comes from the directory name or it can be changed in settings.gradle
version = "1.0"
group = "playground.example"
sourceCompatibility = 1.8
version = "0.1.0"
targetCompatibility = 1.8
description = "A Gradle example project"


repositories {
repositories {
    mavenLocal()
     mavenCentral()
     mavenCentral()
}
configurations.all {
    resolutionStrategy.cacheChangingModulesFor 3600, 'seconds'
}
}


Line 50: Line 31:
configurations {
configurations {
     testImplementation.exclude group: 'com.example'
     testImplementation.exclude group: 'com.example'
}
configurations.all {
    resolutionStrategy.cacheChangingModulesFor 3600, 'seconds'
}
}


Line 64: Line 49:
     main = "io.novaordis.playground.gradle.java.Main"
     main = "io.novaordis.playground.gradle.java.Main"
}
}
</syntaxhighlight>
=Non-Default Build File Name=
The name of the build file can be changed using [[Gradle_Concepts#Project_Descriptor|project descriptors]]:
<syntaxhighlight lang='groovy'>
project(':projectA').buildFileName = 'projectA.gradle'
</syntaxhighlight>
</syntaxhighlight>


Line 80: Line 57:
</syntaxhighlight>
</syntaxhighlight>


=Variables=
=Code=
 
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>
 
=DSL=
 
The following elements are part of [https://docs.gradle.org/current/dsl/org.gradle.api.Project.html Project] API.
 
==configurations.all==
 
Applies enclosed to all [[Gradle_Concepts#Dependency_Configuration|configurations]].
 
<syntaxhighlight lang='groovy'>
configurations.all {
    resolutionStrategy.cacheDynamicVersionsFor 10, 'minutes'
}
</syntaxhighlight>
 
Alternative:


The build script may include general-purpose Java and Groovy code:
<syntaxhighlight lang='groovy'>
<syntaxhighlight lang='groovy'>
configurations.all {
    resolutionStrategy {
        cacheDynamicVersionsFor 10, 'minutes'
    }
}
</syntaxhighlight>


===Configuration===
class Experimental {


====resolutionStrategy====
    private String name;


{{External|https://docs.gradle.org/current/dsl/org.gradle.api.artifacts.ResolutionStrategy.html}}
    Experimental(String name) {


=====cacheDynamicVersionsFor=====
        this.name = name;
 
Configures [[Gradle_Concepts#Dynamic_Version|dynamic version]] caching threshold.
 
<syntaxhighlight lang='groovy'>
resolutionStrategy.cacheDynamicVersionsFor 10, 'minutes'
</syntaxhighlight>
 
=====cacheChangingModulesFor=====
 
==configurations==
 
<syntaxhighlight lang='groovy'>
configurations {
    testCompile.exclude group: 'io.example'
}
</syntaxhighlight>
 
==buildscript==
 
Used when [[Gradle Concepts#External_Plugins|external plugins]] need to be downloaded.
 
<syntaxhighlight lang='groovy'>
buildscript {
    repositories {
        maven { url 'https://plugins.gradle.org/m2/' }
     }
     }
  dependencies {
    classpath 'com.netflix.nebula:gradle-ospackage-plugin:4.3.0'
  }
}
</syntaxhighlight>
==<span id='Repositories'></span>repositories==
{{External|https://docs.gradle.org/current/userguide/declaring_repositories.html}}
[[Gradle Concepts#Repository|Repositories]] are declared in a 'repositories' block:
<syntaxhighlight lang='groovy'>
repositories {
    ...
}
</syntaxhighlight>
Multiple repositories can be declared in the same block. Syntax examples are available for [[Gradle_Concepts#Custom_Maven_Repository|custom Maven repositories]], [[Gradle_Concepts#flatDir|directory-based repositories]], [[Gradle_Concepts#Maven_Central|Maven Central]], etc. The most common setting is declaring that our dependencies are available in Maven Central:
<syntaxhighlight lang='groovy'>
repositories {
    mavenCentral()
}
</syntaxhighlight>


==dependencies==
     @Override
 
     public String toString() {
A DSL element that declares the [[Gradle_Concepts#Dependency|dependencies]] of the [[Gradle_Concepts#Module|module]]. The block lists [[Gradle_Concepts#Dependency_Configuration|dependency configurations]] known to the project, followed by list of dependencies.
         return name;
 
<syntaxhighlight lang='groovy'>
dependencies {
    implementation 'org.slf4j:slf4j-api:1.7.12'
    api 'com.google.guava:guava:23.0'
    ...
}
</syntaxhighlight>
 
Note that the declared dependencies must be available in a declared repository, so [[#repositories|repositories must be declared]].
 
Dependencies can also be declared without a version, and [[Gradle_Concepts#Dependency_Constraint|dependency constraints]] can be used to manage the version, including the transitive versions.
 
<syntaxhighlight lang='groovy'>
dependencies {
     implementation 'org.slf4j:slf4j-api'
     constraints {
         implementation 'org.slf4j:slf4j-api:1.7.12'
     }
     }
}
}
</syntaxhighlight>


When declaring a dependency, a reason for the declaration can be provided in-line:
def experimental = new Experimental("blue");


<syntaxhighlight lang='groovy'>
task test {
dependencies {
     doLast {
     implementation('org.slf4j:slf4j-api:1.7.12') {
         println experimental
         because 'because we like SLF4J'
     }
     }
}
}
</syntaxhighlight>
</syntaxhighlight>
===Dependencies between Subprojects===
[[Gradle_Concepts#Dependencies_Between_Subprojects|Dependencies between the subprojects of the same root project]] must be explicitly declared. If classes belonging to "subproject-B" depend on classes in "subproject-A", then in the [[build.gradle]] of subproject-B we must add:
<syntaxhighlight lang='groovy'>
dependencies {
    ...
    implementation project(':subproject-A')
    ...
}
</syntaxhighlight>
=Multi-Project Configuration=
==allprojects==
The <tt>allprojects</tt> block is used to add configuration items that will apply to all [[Gradle_Concepts#Multi-Project_Build|sub-projects]], as well as the root project.
<syntaxhighlight lang='groovy'>
allprojects {
  repositories {
    ...
  }
}
</syntaxhighlight>
"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 <tt>subprojects</tt> block is used to add configuration times for sub-projects only.
<syntaxhighlight lang='groovy'>
subprojects {
    ...
}
</syntaxhighlight>
=Custom Tasks=
{{Internal|Gradle Custom Task#Overview|Custom Tasks}}
=Respond to Build Lifecycle Events=
Example of how to respond to [[Gradle_Concepts#Build_Phases|project build lifecycle events]].
<syntaxhighlight lang='groovy'>
allprojects {
      afterEvaluate { project ->
          if (project.hasTests) {
              println "Adding test task to $project"
              project.task('test') {
                  doLast {
                        println "running tests for $project"
                  }
              }
          }
    }
}
</syntaxhighlight>
<syntaxhighlight lang='groovy'>
gradle.afterProject {project, projectState ->
      if (projectState.failure) {
          println "Evaluation of $project FAILED"
      } else {
          println "Evaluation of $project succeeded"
      }
}
</syntaxhighlight>
=Respond to Task Lifecycle Events=
Examples of how to respond to [[Gradle_Concepts#Task|task]] lifecycle events.
==Task Creation==
<syntaxhighlight lang='groovy'>
tasks.whenTaskAdded { task ->
      task.ext.srcDir = 'src/main/java'
}
</syntaxhighlight>
==Task Execution==
<syntaxhighlight lang='groovy'>
gradle.taskGraph.beforeTask { Task task ->
      println "executing $task ..."
}
gradle.taskGraph.afterTask { Task task, TaskState state ->
      if (state.failure) {
          println "FAILED"
      }
      else {
          println "done"
      }
}</syntaxhighlight>

Latest revision as of 22:10, 11 October 2020

External

Internal

Overview

build.gradle is referred to as an Gradle build script. It is the script interface to a Project instance.

Example

apply plugin: 'java'

// name comes from the directory name or it can be changed in settings.gradle
group = "playground.example"
version = "0.1.0"
description = "A Gradle example project"

repositories {
    mavenLocal()
    mavenCentral()
}

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

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

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

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

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

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

Comments

// This is a comment

Code

The build script may include general-purpose Java and Groovy code:

class Experimental {

    private String name;

    Experimental(String name) {

        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }
}

def experimental = new Experimental("blue");

task test {
    doLast {
        println experimental
    }
}