Dark theme | Light theme

June 5, 2018

Gradle Goodness: Enable Task Based On Offline Command Line Argument

One of the command line options of Gradle is --offline. With this option we run Gradle in offline mode to indicate we are not connected to network resources like the internet. This could be useful for example if we have defined dependencies in our build script that come from a remote repository, but we cannot access the remote repository, and we still want to run the build. Gradle will use the locally cached dependencies, without checking the remote repository. New dependencies, not already cached, cannot be downloaded of course, so in that scenario we still need a network connection.

We can check in our build script if the --offline command line argument is used. We can use this to disable tasks that depend on network resources so the build will not fail. To see if we invoked our build with the --offline option we can access the property gradle.startParameter.offline. The value is true if the command line argument --offline is used and false if the command line argument is not used.

In the following example build file we use the task type VfsCopy from the VFS Gradle Plugin to define a new task download. The task will download the file index.html from the site We enable the task if the --offline command line argument is not used. If the argument is used the task is disabled.

buildscript {
    repositories {
    dependencies {
        classpath 'org.ysb33r.gradle:vfs-gradle-plugin:1.0'
        classpath 'commons-httpclient:commons-httpclient:3.1'

task download(type: org.ysb33r.gradle.vfs.tasks.VfsCopy) {
    description = 'Downloads index.html from'
    group = 'Remote'

    // Only enable task when we don't use
    // the --offline command line argument.
    enabled = !gradle.startParameter.offline

    from ''
    into project.file("${buildDir}/downloads")

Let's run the download task with and without the --offline option:

$ gradle download --offline --console=plain
> Task :download SKIPPED

$ gradle download --console=plain
> Task :download

1 actionable task: 1 executed

Written with Gradle 4.8.