Search

Dark theme | Light theme
Showing posts with label GradleGoodness:Configuration. Show all posts
Showing posts with label GradleGoodness:Configuration. Show all posts

February 25, 2024

Gradle Goodness: Using System Properties Lazily

It is good practice in Gradle to use lazy configuration. This makes builds faster as only configuration values are evaluated when needed. We should try to not let Gradle spend time on evaluating configuration values that will not be used. For example tasks that are not executed could still be configured by Gradle. If we make sure the configuration of these tasks is lazy we can save time.

Gradle gives us a lazy way to get the value of a Java system property. In our build script we can use the providers property of type ProviderFactory and the method systemProperty(String). This method returns a Provider<String> instance that can be used to get the value of a system property in a lazy way. The method systemProperty can also be used with a Provider<String> argument.

In the following example we register a task that prints the value of the Java system property user.name to the console. We use lazy configuration to make sure the value of the system property is only fetched when the task is executed.

tasks {
    register<PrintSystemProperty>("printSystemProperty") {
        // We can use providers.systemProperty(String)
        // to get the value of an Java system property
        // in a lazy way.
        // The argument can also be a Provider<String> type.
        // So at this point the value is not fetched yet,
        // only when the task is executed the actual value
        // of the system property "user.name" is fetched.
        systemProperty = providers.systemProperty("user.name")
    }
}

// Simple task to print the value of a Java system property.
abstract class PrintSystemProperty : DefaultTask() {
    @get:Input
    abstract val systemProperty: Property<String> // Use lazy property.

    @TaskAction
    fun printSystemPropertyValue() {
        // Only here we actually will get the value
        // for the system property.
        logger.quiet(systemProperty.get())
    }
}
$ ./gradlew printSystemProperty

> Task :printSystemProperty
mrhaki

BUILD SUCCESSFUL in 685ms
2 actionable tasks: 2 executed

Written with Gradle 8.6.

December 2, 2022

Gradle Goodness: Set Project Version In Version Catalog

The version catalog in Gradle is very useful to have one place in our project to define our project and plugin dependencies with their versions. But we can also use it to define our project version and then refer to that version from the version catalog in our build script file. That way the version catalog is our one place to look for everything related to a version. In the version catalog we have a versions section and there we can define a key with a version value. The name of the key could be our project or application name for example. We can use type safe accessors generated by Gradle in our build script to refer to that version.

In the following example build script written with Kotlin we see how we can refer to the version from the version catalog:

// File: build.gradle.kts
description = "Sample project for Gradle version catalog"
    
// Set version using version catalog.
version = libs.versions.app.version.get()
    
// We can use the TaskContainer to keep all
// task related things in one place.
tasks {
    // Register a new task to print out the project version.
    register("projectVersion") {
        doLast {
            println("Project version: " + version)
        }
    }
}

And the version catalog is defined in the following file:

# File: gradle/libs.versions.toml
[versions]
app-version = "2.0.1"

When we run the task projectVersion we see our project version in the output:

$ gradle projectVersion

> Task :projectVersion
Project version: 2.0.1

BUILD SUCCESSFUL in 831ms
1 actionable task: 1 executed
$

Written with Gradle 7.6.

April 19, 2017

Gradle Goodness: Change Local Build Cache Directory

Gradle 3.5 introduced the build cache. With the build cache we can reuse task output from builds that can come from different computers. We can also use the build cache feature for our local builds. By default the directory to store the cache is located in the Gradle user home directory on our computer (USER_HOME/.gradle/caches/build-cache-1). We can change the directory for the local cache via settings.gradle of our Gradle project. For example we could configure a directory in our project file structure to be the build cache directory. Then it is easy to clean the cache, because it is a directory not shared by other Gradle projects. With the default directory location in the Gradle user home directory the caches of all Gradle projects we run on our computer are stored in a single directory. And the cache doesn't shrink and will only grow we might want to have more control of where the cache of a single Gradle project is stored. This way we can easily clean the cache, because all files of a project are stored in the directory for that project.

In the following example settings.gradle file we configure our build cache directory to be the directory build-cache in the root directory of our project where we store our settings.gradle file:

// File: settings.gradle
buildCache {
    local {
        // Set local build cache directory.
        directory = "${settingsDir}/build-cache"
    }
}

Written with Gradle 3.5.

September 30, 2016

Gradle Goodness: Add But Do Not Apply Plugin Using Plugins Block

Sometimes we want to include the classes from a plugin, like tasks, in our build class path without actually applying the plugin. Or we want to add the classes to the root project and actually apply the plugin in subprojects. We can achieve this with a buildScript block and add the plugin dependency to the classpath configuration. But we can also do this with the newer plugins configuration block. Inside the plugins block we define the id and the version of the plugin, and since Gradle 3.0 we can also use the apply method. We have to set the value false to include the plugin to the class path, but not apply it to the project.

In the following example we add the Asciidoctor plugin to our build file, but we only want to use the AsciidoctorTask task from this plugin.

plugins {
    // Add Asciidoctor plugin, but do not apply it.
    id 'org.asciidoctor.convert' version '1.5.3' apply false
}

configurations {
    convert
}

repositories {
    jcenter()
}

dependencies {
    convert 'org.asciidoctor:asciidoctorj:1.5.4'
}

// Use of Asciidoctor task from the Asciidoctor plugin.
task convert(type: org.asciidoctor.gradle.AsciidoctorTask) {
    classpath = configurations.convert
}

Another use case can be that we have a multi-project build. We want to configure all plugins in a plugins configuration block in the root build file. And based on certain conditions we want to actually apply the plugin to a subproject. In the following example we add the Asciidoctor plugin and apply it to all subprojects where the name ends -doc:

plugins {
    id 'org.asciidoctor.convert' version '1.5.3' apply false
}

subprojects {
    if (name.endsWith('-doc')) {
        apply plugin: 'org.asciidoctor.convert'
    }
}

Written with Gradle 3.1.

September 14, 2016

Gradle Goodness: Lazy Project Property Evaluation

Sometime we need to define a project property in our Gradle build file for which the value must be evaluated later than the assignment. We can do this in different ways in Gradle. For example for a String type property we can rely on Groovy's support for lazy String evaluation. If the property is of a different type we can use Closure to define the value. The Closure code is not executed during the configuration phase directly, but we can write code to invoke the Closure at the right moment and get the value. Finally we can use the afterEvaluate method of the Project class to define a lazy property. Let's look at the different options we have with some code samples.

First we look at a lazy String property. We illustrate this with an example of a multi-project build with the following layout:

.
├── api
├── app
├── build.gradle
├── lib
└── settings.gradle

In our settings.gradle file we define the projects we want to be part of the root project:

include 'api'
include 'lib'
include 'app'

Let's create a build file with a lazy property buildVersion:

subproject {

    version = '1.0.0'

    // Use lazy String evaluation using
    // the ${->...} syntax. If we don't
    // make it lazy the value of project.version
    // is always 1.0.0, because that is the only
    // known value at this point and the changed value
    // in the app project is not noticed.
    ext.buildVersion = "${project.name}-${-> project.version}"

    task displayBuildVersion {
        description = 'Display value of buildVersion property'
        doFirst {
            println buildVersion
        }
    }

}

project('app') {
    // In the project app we define
    // a different value for the version
    // property. Remember this property
    // is used in the definition of the
    // buildVersion property.
    version = '1.0.3'
}

If we run the displayBuildVersion task we get the following output:

$ gradle -q displayBuildVersion

api-1.0.0
app-1.0.3
lib-1.0.0
$

If we have a property of another type than String we can use another mechanism to support lazy properties. We use a Closure to define the value and then invoke the Closure to calculate the value at a later time. In the next build script we add a support method lazyProperty to check if the property is defined with a Closure. If so we execute the Closure to calculate the value. Any other type is return as-is.

subprojects {

    ext {
        // Project property with Integer value.
        // Value is overriden in the 'app' project.
        port = 80

        // Value is lazy and depends on port
        // property. Port property can be overriden
        // later in the configuration phase of Gradle.
        // Using a Closure we can make the value
        // calculation at a later point in time.
        calculatedPort = { port + 10 }
    }

    task displayCalculatedPort {
        description = 'Display value of calculatedPort property'
        doFirst {
            print "Calculated port for ${project.name} "
            println lazyProperty(project, 'calculatedPort')
            // Alternative without support method:
            // println project.property('calculatedPort')()
            // Or even shorter:
            // println calculatedPort()
        }
    }

}

project('app') {
    // Override port property.
    ext.port = 8000
}

/**
 * Check if property value is a Closure. If so the value
 * is calculated by running the Closure and returned. 
 * Otherwise the value is returned without calculation.
 *
 * @param project Project containing the property to calculate.
 * @param propertyName Name of the property to calculate value for.
 */
def lazyProperty(final Project project, final String propertyName) {
    // Get property.
    def propertyValue = project.property(propertyName)

    // Check for type of property to see if we can
    // run it as a Closure.
    if (propertyValue instanceof Closure) {
        // Invoke Closure to calculate the value.
        propertyValue()
    } else {
        // Return value as-is.
        propertyValue
    }
}

Let's run the displayBuildVersion task and look at the output:

$ gradle -q displayCalculatedPort

Calculated port for api 90
Calculated port for app 8010
Calculated port for lib 90
$

Finally we use the afterEvaluate method:

subprojects {

    // Project property with Integer value.
    // Value is overriden in the 'app' project.
    ext.port = 80

    afterEvaluate {
        // Create calculatedPort property with
        // value at the latest moment.
        ext.calculatedPort = port + 10
    }

    task displayCalculatedPort {
        description = 'Display value of calculatedPort property'
        doFirst {
            print "Calculated port for ${project.name} "
            println calculatedPort
        }
    }

}

project('app') {
    // Override port property.
    ext.port = 8000
}

When we run the displayBuildVersion task and look at the output we see expected results:

$ gradle -q displayCalculatedPort

Calculated port for api 90
Calculated port for app 8010
Calculated port for lib 90
$

In our simple examples we used the lazy project property only in one task. We could have simply evaluated the value in the task definition as it is the only place where it is used. But if a property is used by other tasks and code in our build script we can rely on the mentioned solutions in this blog post.

Written with Gradle 3.0.

October 2, 2015

Gradle Goodness: Setting Global Properties For All Gradle Builds

To define project properties outside the Gradle build file, we can define them in a file gradle.properties in our project directory. If we want to define property values that are used by all Gradle builds we can create a file gradle.properties in the GRADLE_USER_HOME directory. By default this is in the USER_HOME/.gradle directory.

In the following example gradle.properties file we assign values to some properties that can be used in all Gradle builds we run on our computer. We store the file in USER_HOME/.gradle.

# Bintray username and password.
bintrayUser=mrhaki
bintrayPasword={secret}

# Enable Gradle daemon for all builds.
org.gradle.daemon=true

In the following example build file we simply display the values for the bintrayUser and bintrayPoassword global properties:

// File: build.gradle
task showBintrayProps {
    doLast {
        println "Bintray user/password: ${bintrayUser}/${bintrayPassword}"
    }
}

Written with Gradle 2.7.