Gradle Variables and Properties: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
No edit summary
 
(45 intermediate revisions by the same user not shown)
Line 1: Line 1:
=External=
=DEPLETE TO=
 
{{Internal|Gradle Properties - Runtime and Project Configuration|Gradle Properties - Runtime and Project Configuration}}
* https://docs.gradle.org/current/userguide/build_environment.html
 
=Internal=
 
* [[Gradle_Concepts#Variables_and_Properties|Gradle Concepts]]


=Overview=
=Overview=
Line 13: Line 8:
=System Properties=
=System Properties=


A system property in a Gradle runtime context is a regular JVM system property that has no special signification to Gradle. There are a few system properties that make exception from this rule: "gradle.wrapperUser", "gradle.wrapperPassword" and "gradle.user.home".  
A system property in a Gradle runtime context is a regular JVM system property that has no special signification to Gradle. There are a few system properties that make exception from this rule: "gradle.wrapperUser", "gradle.wrapperPassword" and "gradle.user.home". System properties can be declared in command line with -D. The -D option of the gradle command has the same effect as the -D option of the java command.
 
-D<''propName''>=<''propValue''>


System properties can be declared in command line with -D. The -D option of the gradle command has the same effect as the -D option of the java command.
Interestingly enough, inserting an extra "=" between -D and property name also works:


  -D=<''propName''>=<''propValue''>
  -D=<''propName''>=<''propValue''>
Line 56: Line 53:


does not show system properties declared with -D=... on command line, but does show system properties declared with "systemProp." in gradle.properties files.
does not show system properties declared with -D=... on command line, but does show system properties declared with "systemProp." in gradle.properties files.
Also see: {{Internal|Gradle_Pass_Configuration_on_Command_Line|Pass Configuration on Command Line}}


=Gradle Properties=
=Gradle Properties=
Line 65: Line 64:
* Whether [[Gradle_Concepts#The_Gradle_Daemon|Gradle Daemon]] runs or not and its operational parameters.
* Whether [[Gradle_Concepts#The_Gradle_Daemon|Gradle Daemon]] runs or not and its operational parameters.


The Gradle properties can be declared on command line with -D=... or in [[#.27gradle.properties.27_Files|gradle.properties files]]. When the same Gradle property is declared in multiple places, the effective value is subject to the [[#Property_Declaration_Precedence_Rules|property declaration precedence rules]].
The Gradle properties can be declared on command line with -D<propName>=<propValue> or in [[#.27gradle.properties.27_Files|gradle.properties files]]. When the same Gradle property is declared in multiple places, the effective value is subject to the [[#Property_Declaration_Precedence_Rules|property declaration precedence rules]].
 
<syntaxhighlight lang='bash'>
... -Dorg.gradle.debug=true ...
</syntaxhighlight>


=Project Properties=
=Project Properties=


A Gradle project property is a key value pair that can be accessed directly from build scripts without any qualifier. Project properties are a mechanism designed to allow easy access and storage of state in build scripts. A project property can be accessed without any qualifier:
A Gradle project property is a key value pair that can be accessed directly from build scripts without any qualifier.  
 
{{Note|A project property is an [[#Extra_Properties|extra property]] defined on a project instance.}}
 
Project properties are a mechanism designed to allow easy access and storage of state in build scripts. A project property can be accessed without any qualifier:


<syntaxhighlight lang='groovy'>
<syntaxhighlight lang='groovy'>
Line 79: Line 86:
</syntaxhighlight>
</syntaxhighlight>


An important characteristic of project properties is that an attempt to access a project property that was not explicitly defined will trigger a build error.
All properties currently declared on a project instance and their values can be displayed with:
 
<syntaxhighlight lang='groovy'>
task displayProjectProperties {
 
    doLast() {


<font color=red>FAILURE: Build failed with an exception.</font>
        for(Map.Entry p: project.getProperties()) {
            println p;
* Where:
        }
Build file '/Users/ovidiu/playground/gradle/concepts/build.gradle' line: 11
    }
}
* What went wrong:
</syntaxhighlight>
Execution failed for task ':printProps'.
> <font color=red>Could not get unknown property 'thisProjectPropertyWasNotDefined'</font> for task ':printProps' of type org.gradle.api.DefaultTask.


To avoid a build-time exception and build failure, the existence of a project property can be checked in the configuration scripts with:
To avoid a [[#Project_Property_Lookup_Failure|build-time exception and build failure]], the existence of a project property can be checked in the configuration scripts with:


<syntaxhighlight lang='groovy'>
<syntaxhighlight lang='groovy'>
Line 118: Line 128:
When the same project property is declared in multiple places, the effective value is subject to the [[#Property_Declaration_Precedence_Rules|property declaration precedence rules]].
When the same project property is declared in multiple places, the effective value is subject to the [[#Property_Declaration_Precedence_Rules|property declaration precedence rules]].


=Plugin Properties=
==Project Property Lookup Failure==


Plugins add specific properties. For a list of properties added by various plugins, consult the [[Gradle_Plugins#Plugin_List|plugin pages]].
An important characteristic of project properties is that an attempt to access a project property that was not explicitly defined will trigger a build error.


=Declaring Variables and Properties in Configuration Files=
<font color=red>FAILURE: Build failed with an exception.</font>
 
Configuration scripts can declare variables during the [[Gradle_Concepts#Initialization|initialization]] and [[Gradle_Concepts#Configuration|configuration]] phases, and the values of those variables can be accessed and updated during the [[Gradle_Concepts#Execution|execution]] phase and used to drive build logic. There are two types of variables that can be declared: [[#Local_Variables|local variables]] and [[#Extra_Properties|extra properties]].
 
==Extra Properties==
 
An ''extra property'' is a property that can be declared on most model object instances available to the closure being executed. In case of a settings script, the available model objects are Settings, Gradle, ProjectDescriptor, etc., but of those ProjectDescriptor does not allow defining extra properties, and Settings, even if allows defining extra properties, cannot be easily accessed at configuration and execution phase, so the best candidate for defining extra properties is Gradle. For build scripts, extra properties can be defined on any available object model instances, and the most common object to define properties on is the Project instance, making them [[#Project_Properties|project properties]]. They can be declared with a special syntax described below. Once the properties have been declared, they can be read and set like predefined properties. Extra properties can be accessed from anywhere their owning object can be accessed, giving them a wider scope than [[#Local_Variable|local variables]]. Extra properties on a project are visible from its sub-projects.
 
By requiring special syntax for adding a property, Gradle can fail fast when an attempt is made to set a [[#Predefined_Properties|predefined]] or [[#Extra_Properties|extra property]] but the property is misspelled or does not exist.
 
===Declaring and Using Extra Properties===
 
The extra properties are declared using the "ext" DSL keyword, applied to the model object we intend to declare extra properties for. However, "ext" is not necessary to access the property once declared, as shown in the examples below:
 
====Initialization Phase====
 
The property is defined in settings.gradle:
 
<syntaxhighlight lang='groovy'>
...
gradle.ext.color = "blue"
...
</syntaxhighlight>
 
The property can be accessed anywhere in a build or settings script:
 
<syntaxhighlight lang='groovy'>
println "gradle is $gradle.color"
</syntaxhighlight>
 
====Extra Properties and Multi-Project Builds====
 
The extra properties are not available and throw an execution error if they are accessed before are defined. That is why a multi-project build that declares extra properties in sub-projects' build.gradle and attempts to use them in the root project build.gradle will fail at the configuration phase:
 
BUILD FAILED in 3s
   
   
...
  * Where:
  Build file '/Users/ovidiu/playground/gradle/concepts/build.gradle' line: 11
  * <font color=red>Where</font>:
  Build file '.../<font color=red>root-project/build.gradle</font>' line: 17
   
   
  * What went wrong:
  * What went wrong:
  A problem occurred <font color=red>evaluating root project 'root-project'</font>.
  Execution failed for task ':printProps'.
> Could not get unknown property 'blah' <font color=red>for project ':sub-project-A'</font> of type org.gradle.api.Project.
> <font color=red>Could not get unknown property 'thisProjectPropertyWasNotDefined'</font> for task ':printProps' of type org.gradle.api.DefaultTask.


The error occurs even "blah" was declared in sub-project-A's build.gradle, because the build file was not evaluated at the time the root project file is executed. If we log build.gradle evaluation, we get something like:
==<span id='Predefined_Properties'></span><span id='Project_Coordinates'></span><span id='name'></span><span id='group'></span><span id='version'></span><span id='parent'></span><span id=''></span><span id='Other_Properties'></span><span id='project'></span><span id='projectDir'></span><span id='path'></span><span id='description'></span><span id='displayName'></span><span id='buildDir'></span><span id='buildFile'></span><span id='rootDir'></span><span id='rootProject'></span><span id='rootProject.name'></span><span id='state'></span><span id='status'>Project Property List==


exiting root project build.gradle ....
For a complete list of project properties see: {{Internal|Gradle Project Properties TODEPLETE#Overview|Project Properties}}
entering sub-project-A build.gradle ....
exiting sub-project-A build.gradle ....


which shows that the sub-project build script is executed after the root project build script is executed.
=Plugin Properties=


====At Configuration Phase====
Plugins add specific properties. For a list of properties added by various plugins, consult the [[Gradle_Plugins#Plugin_List|plugin pages]].


The property can be declared in a build script as follows:
=Declaring Variables and Properties in Configuration Files=


<syntaxhighlight lang='groovy'>
Configuration scripts can declare variables during the [[Gradle_Concepts#Initialization|initialization]] and [[Gradle_Concepts#Configuration|configuration]] phases, and the values of those variables can be accessed and updated during the [[Gradle_Concepts#Execution|execution]] phase and used to drive build logic. There are two types of variables that can be declared: [[#Local_Variables|local variables]] and [[#Extra_Properties|extra properties]].
project.ext.isApi = true
</syntaxhighlight>


The property can be accessed anywhere in a build script:
==<span id='Local_Variable'></span>Local Variables==
 
<syntaxhighlight lang='groovy'>
println isApi
</syntaxhighlight>


Declaring multiple extra properties in a closure:
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. The scope include all closures declared in scope.


<syntaxhighlight lang='groovy'>
<syntaxhighlight lang='groovy'>
def myVariable = "something"
...
...
ext {
println myVariable
    log4jVersion = "2.1.7"
    emailNotification = "build@example.com"
}
...
</syntaxhighlight>
</syntaxhighlight>


Line 210: Line 173:
  project.name
  project.name


are equivalent. Normally, using "name" is sufficient. In case you define a property or a method which has the same name as a member of the Project object, you will need to use the <tt>project</tt> property.
are equivalent. Normally, using "name" is sufficient. In case you define a property or a method which has the same name as a member of the Project object, you will need to use the <tt>project</tt> property.
 
If auto-delegation is used, the build script [[#Project_Property_Lookup_Failure|will fail]] if the property was not previously defined on the Project instance.


=Property Declaration Precedence Rules=
=Property Declaration Precedence Rules=
Line 225: Line 190:


==='gradle.properties' Files===
==='gradle.properties' Files===
'gradle.properties' files are also used to define properties. There are two kinds of 'gradle.properties' files. If both files are present, their content is merged and the configuration that comes from the user home directory takes precedence over the configuration that comes from the project root directory. Form a security perspective, it makes sense to use the user home directory if the project is checked into a repository and we do not want to maintain sensitive information in that file. The project root gradle.properties is important because it can be stored in source control, so the entire team working on the project can share the same configuration.
====Gradle User Home gradle.properties====
This file is  stored in Gradle user home directory ~/.gradle/gradle.properties, conventionally referred to as GRADLE_USER_HOME.
====Project Root gradle.properties====


===Environment Variables===
===Environment Variables===
Line 246: Line 203:
This feature is useful when you don’t have admin rights to a continuous integration server and you need to set property values that should not be easily visible. Since you cannot use the -P option in that scenario, nor change the system-level configuration files, the correct strategy is to change the configuration of your continuous integration build job, adding an environment variable setting that matches an expected pattern. This won’t be visible to normal users on the system.
This feature is useful when you don’t have admin rights to a continuous integration server and you need to set property values that should not be easily visible. Since you cannot use the -P option in that scenario, nor change the system-level configuration files, the correct strategy is to change the configuration of your continuous integration build job, adding an environment variable setting that matches an expected pattern. This won’t be visible to normal users on the system.


=Predefined Properties=
=Passing Configuration to a Gradle Build via Custom Environment Variables=
 
==Project Coordinates==
 
===name===
 
A String containing the name of the project directory. It automatically becomes the project's [[Gradle_Project_and_Build_Script#Project_Name.2C_artifactId|name]] coordinate. See [[Gradle_Project_and_Build_Script#Project_Coordinates|Gradle Project Coordinates]].
 
===group===
 
See [[Gradle_Project_and_Build_Script#Group.2C_groupId|Gradle Project Coordinates - Group]].
 
===version===
 
See [[Gradle_Project_and_Build_Script#Version|Gradle Project Coordinates - Version]].
 
===parent===
 
==Other Properties==
 
===project===
 
The Project instance.
 
===projectDir===
 
The File instance corresponding to the directory containing the build script.
 
===path===
 
A String containing the absolute path of the project. The path of the root project is ":"
 
===description===
 
A String containing the description for the project.
 
===displayName===
 
===buildDir===
 
A File representing <''projectDir''>/build.
 
===buildFile===
 
===rootDir===
 
===rootProject===
 
====rootProject.name====
 
===state===


===status===
{{Internal|Passing Configuration to a Gradle Build via Custom Environment Variables#Overview|Passing Configuration to a Gradle Build via Custom Environment Variables}}

Latest revision as of 22:05, 13 October 2020

DEPLETE TO

Gradle Properties - Runtime and Project Configuration

Overview

Gradle uses system properties, Gradle properties, project properties and, being a Groovy extension, local variables. When a property with the same name is declared in multiple places, property declaration precedence rules apply.

System Properties

A system property in a Gradle runtime context is a regular JVM system property that has no special signification to Gradle. There are a few system properties that make exception from this rule: "gradle.wrapperUser", "gradle.wrapperPassword" and "gradle.user.home". System properties can be declared in command line with -D. The -D option of the gradle command has the same effect as the -D option of the java command.

-D<propName>=<propValue>

Interestingly enough, inserting an extra "=" between -D and property name also works:

-D=<propName>=<propValue>

System properties can also be declared in gradle.properties files with a special syntax:

systemProp.<propName>=<propValue>

The "systemProp." system properties set in a multi-project build gradle.properties files in any project except root will be ignored. Only the root project's gradle.properties will be checked for properties that begin with "systemProp." prefix.

When the same system property is declared in multiple places, the effective value is subject to the property declaration precedence rules.

There are no special syntactic facilities to access system properties from build scripts, unlike project properties that have a special simplified syntax for access. System properties can be accessed as follows:

task printProp {

    doLast {

        println System.properties['mySystemPropA']
        println System.getProperty('mySystemPropA')
    }
}

All other equivalent JDK API is available:

System.getProperty('myPropertyName', 'DefaultValue')

If we know that the system property has boolean semantics, we can use:

Boolean.getBoolean(...)

Note that an attempt to access a non-existent system property from a build script won't trigger a build error, it will simply return null.

gradle properties 

does not show system properties declared with -D=... on command line, but does show system properties declared with "systemProp." in gradle.properties files.

Also see:

Pass Configuration on Command Line

Gradle Properties

These are properties that can be used to configure aspects of a Gradle build run, regardless of the specific of the project being built. They can be seen as Gradle runtime configuration options, and can be used to configure the following aspects:

The Gradle properties can be declared on command line with -D<propName>=<propValue> or in gradle.properties files. When the same Gradle property is declared in multiple places, the effective value is subject to the property declaration precedence rules.

 ... -Dorg.gradle.debug=true ...

Project Properties

A Gradle project property is a key value pair that can be accessed directly from build scripts without any qualifier.


A project property is an extra property defined on a project instance.

Project properties are a mechanism designed to allow easy access and storage of state in build scripts. A project property can be accessed without any qualifier:

task printProp {
  doLast {
    println myProjectProp
  }
}

All properties currently declared on a project instance and their values can be displayed with:

task displayProjectProperties {

    doLast() {

        for(Map.Entry p: project.getProperties()) {
            println p;
        }
    }
}

To avoid a build-time exception and build failure, the existence of a project property can be checked in the configuration scripts with:

project.hasProperty("somePropertyName")

The following example shows the pattern to initialize a project property with a default value, and thus preventing build failure if the property was not declared externally on command line or gradle.properties files. For more details on how to declare project properties in the build scripts, see Extra Properties.

if (!project.hasProperty("ciUsername")) {
  ext.ciUsername = "CI-USERNAME-SHOULD-BE-DEFINED-EXTERNALLY"
}

Project properties can be declared on command line with:

-P<projectPropName>=<value>

An equivalent effect can be achieved declaring the project property with -D, as with the system properties, but prefixing it with "org.gradle.project.". A property declared as such becomes a project property and can be accessed from the build script without any qualification:

... -Dorg.gradle.project.myProjectPropB=green ...

Project properties can also be declared in gradle.properties files:

someProperty=someValue

When the same project property is declared in multiple places, the effective value is subject to the property declaration precedence rules.

Project Property Lookup Failure

An important characteristic of project properties is that an attempt to access a project property that was not explicitly defined will trigger a build error.

FAILURE: Build failed with an exception.

* Where:
Build file '/Users/ovidiu/playground/gradle/concepts/build.gradle' line: 11

* What went wrong:
Execution failed for task ':printProps'.
> Could not get unknown property 'thisProjectPropertyWasNotDefined' for task ':printProps' of type org.gradle.api.DefaultTask.

Project Property List

For a complete list of project properties see:

Project Properties

Plugin Properties

Plugins add specific properties. For a list of properties added by various plugins, consult the plugin pages.

Declaring Variables and Properties in Configuration Files

Configuration scripts can declare variables during the initialization and configuration phases, and the values of those variables can be accessed and updated during the execution phase and used to drive build logic. There are two types of variables that can be declared: 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. The scope include all closures declared in scope.

def myVariable = "something"
...
println myVariable

Auto-Delegation

Properties not defined in the build script are auto-delegating to the Project instance. For example:

name

and

project.name

are equivalent. Normally, using "name" is sufficient. In case you define a property or a method which has the same name as a member of the Project object, you will need to use the project property.

If auto-delegation is used, the build script will fail if the property was not previously defined on the Project instance.

Property Declaration Precedence Rules

Properties can be declared implicitly by command line flags, explicitly on command line with -D or -P, in gradle.properties files or environment variables. These configuration methods are listed in the descending order of their precedence, with the highest precedence at the top. The first one encountered wins.

Command Line Flags

Command line flags have precedence over properties and environment variables with the same effect. For more details see Gradle Command Line.

Command Line Property Definitions

System properties can be declared with -D on command line. Project properties can be declared with -P on command line.

'gradle.properties' Files

Environment Variables

Environment variables such as GRADLE_OPTS and JAVA_OPTS are sourced by the environment that executes Gradle. These environment variables can be used to provide properties definition, but they are only available in a specific user's environment, and do not propagate to version control.

GRADLE_USER_HOME specifies Gradle user home directory, which is $USER_HOME/.gradle by default.

Project properties can also be set as environment variables:

ORG_GRADLE_PROJECT_<propName>=<propValue>

This feature is useful when you don’t have admin rights to a continuous integration server and you need to set property values that should not be easily visible. Since you cannot use the -P option in that scenario, nor change the system-level configuration files, the correct strategy is to change the configuration of your continuous integration build job, adding an environment variable setting that matches an expected pattern. This won’t be visible to normal users on the system.

Passing Configuration to a Gradle Build via Custom Environment Variables

Passing Configuration to a Gradle Build via Custom Environment Variables