Gradle Variables and Properties: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
No edit summary
 
(133 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
=Overview=


=Internal=
Gradle uses [[#System_Properties|system properties]], [[#Gradle_Properties|Gradle properties]], [[#Project_Properties|project properties]] and, being a Groovy extension, [[#Local_Variables|local variables]]. When a property with the same name is declared in multiple places, [[#Property_Declaration_Precedence_Rules|property declaration precedence rules]] apply.


=Overview=
=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 [[#.27gradle.properties.27_Files|gradle.properties files]] with a special syntax:


=Property Concepts=
systemProp.<''propName''>=<''propValue''>


==System Properties==
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.


A system property is this context is a regular JVM system property, that has no special signification to Gradle. There are no special facilities to access system properties from build scripts (unlike project properties, that have a special simplified syntax for access):
When the same system property is declared in multiple places, the effective value is subject to the [[#Property_Declaration_Precedence_Rules|property declaration precedence rules]].


A system property can be accessed from a build script as follows:
There are no special syntactic facilities to access system properties from build scripts, unlike [[#Project_Properties|project properties]] that have a special simplified syntax for access. System properties can be accessed as follows:


<syntaxhighlight lang='groovy'>
<syntaxhighlight lang='groovy'>
Line 26: Line 37:
</syntaxhighlight>
</syntaxhighlight>


Note that an attempt to access a non-existent system property won't trigger a build error, it will simply return null.
All other equivalent JDK API is available:
<syntaxhighlight lang='groovy'>
System.getProperty('myPropertyName', 'DefaultValue')
</syntaxhighlight>
 
If we know that the system property has boolean semantics, we can use:


==Gradle Properties==
<syntaxhighlight lang='groovy'>
Boolean.getBoolean(...)
</syntaxhighlight>
 
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_Operations#properties|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: {{Internal|Gradle_Pass_Configuration_on_Command_Line|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:
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:
Line 36: 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.


==Project Properties==
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]].


A Gradle project property is a key value pair that [[#Accessing_Project_Properties|can be accessed directly from build scripts without any qualifier]] - it can be considered logically attached directly to the project.  
<syntaxhighlight lang='bash'>
... -Dorg.gradle.debug=true ...
</syntaxhighlight>


An important characteristic of project properties is that an attempt to access a project property that was not explicitly defined using [[#Declaring_Properties|one of the means described below]] will trigger a build error.
=Project Properties=
 
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'>
task printProp {
task printProp {
     doLast {
  doLast {
      println someProjectProperty
    println myProjectProp
  }
  }
}
</syntaxhighlight>
 
All properties currently declared on a project instance and their values can be displayed with:
 
<syntaxhighlight lang='groovy'>
task displayProjectProperties {
 
     doLast() {
 
        for(Map.Entry p: project.getProperties()) {
            println p;
        }
    }
}
</syntaxhighlight>
 
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'>
project.hasProperty("somePropertyName")
</syntaxhighlight>
 
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|Extra Properties]].
 
<syntaxhighlight lang='groovy'>
if (!project.hasProperty("ciUsername")) {
  ext.ciUsername = "CI-USERNAME-SHOULD-BE-DEFINED-EXTERNALLY"
}
}
</syntaxhighlight>
</syntaxhighlight>
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_Properties|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|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.


  <font color=red>FAILURE: Build failed with an exception.</font>
  <font color=red>FAILURE: Build failed with an exception.</font>
Line 57: Line 139:
  * What went wrong:
  * What went wrong:
  Execution failed for task ':printProps'.
  Execution failed for task ':printProps'.
  > <font color=red>Could not get unknown property 'someProjectProperty'</font> for task ':printProps' of type org.gradle.api.DefaultTask.
  > <font color=red>Could not get unknown property 'thisProjectPropertyWasNotDefined'</font> for task ':printProps' of type org.gradle.api.DefaultTask.


=Declaring Properties=
==<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==


These configuration methods are listed in the descending order of their precedence, with the highest precedence at the top. The first one encountered wins.
For a complete list of project properties see: {{Internal|Gradle Project Properties TODEPLETE#Overview|Project Properties}}


==Command Line Flags==
=Plugin Properties=


Command line flags have precedence over properties and environment variables with the same effect. See: {{Internal|Gradle_Operations#Command_Line|Gradle Command Line}}
Plugins add specific properties. For a list of properties added by various plugins, consult the [[Gradle_Plugins#Plugin_List|plugin pages]].


==Command Line Property Definitions==
=Declaring Variables and Properties in Configuration Files=


===Command Line System  Properties===
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]].


[[#System_Properties|System properties]] can be declared on command line with "-D=", using the usual Java system property declaration syntax:
==<span id='Local_Variable'></span>Local Variables==


... -DsystemProp1=red ...
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.


===Command Line Project Properties===
<syntaxhighlight lang='groovy'>
def myVariable = "something"
...
println myVariable
</syntaxhighlight>


[[#Project_Properties|Project properties]] can be declared on command line with "-P="
=Auto-Delegation=


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


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_Properties|project property]] and can be accessed from the build script without any qualification:
name


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


==gradle.properties Files==
project.name


<font color=darkgray><tt>gradle.properties</tt> can be used to define [[#Properties|properties]] for the build. <tt>gradle.properties</tt> files can be placed either in Gradle user home directory (~/.gradle/gradle.properties) or in the project root directory.  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. If a command line -D''property-name''=... is specified, the value overrides the value read from the property files, if any.
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.  


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.
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.


<syntaxhighlight lang='groovy'>
=Property Declaration Precedence Rules=
someUser=someuser
somePassword=somepassword
</syntaxhighlight>


</font>
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.


===Gradle User Home gradle.properties===
===Command Line Flags===


This location is configurable as GRADLE_USER_HOME environment variable.
Command line flags have precedence over properties and environment variables with the same effect. For more details see [[Gradle_Operations#Command_Line|Gradle Command Line]].


===Project Root gradle.properties===
===Command Line Property Definitions===


This property definition vehicle is important because it can be stored in source control, so the entire team working on the project can share the same configuration.
[[#System_Properties|System properties]] can be declared with -D on command line. [[#Project_Properties|Project properties]] can be declared with -P on command line.


==Environment Variables==
==='gradle.properties' Files===


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|properties]] definition, but they are only available in a specific user's environment, and do not propagate to version control. For definitions that propagate to version control, so an entire team can use them, use the [[#Project_Root_gradle.properties|project root gradle.properties]].
===Environment Variables===


=Accessing Properties=
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|properties]] definition, but they are only available in a specific user's environment, and do not propagate to version control.


The effective value of the properties can be displayed with:
GRADLE_USER_HOME specifies Gradle user home directory, which is $USER_HOME/.gradle by default.


gradle properties
Project properties can also be set as environment variables:


==Accessing Gradle Properties==
ORG_GRADLE_PROJECT_<''propName''>=<''propValue''>


<syntaxhighlight lang='groovy'>
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.
</syntaxhighlight>
 
==Accessing Project Properties==
 
A project property can be accessed without any qualifier:
 
<syntaxhighlight lang='groovy'>
task printProp {
 
    doLast {
 
        println myProjectProp
    }
}
</syntaxhighlight>


=TODO=
=Passing Configuration to a Gradle Build via Custom Environment Variables=


{{Internal|Tmp|tmp}}
{{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