February 1, 2017

Gradle Goodness: Check Operating System In Build Scripts

Sometimes we want to check which operating system is used in our build script. For example we have tasks that need to run if the operating system is Windows and not for other operating systems. Gradle has an internal class org.gradle.nativeplatform.platform.internal.DefaultOperatingSystem, but we should not use this class in our build scripts. The class is used internally by Gradle and can change without warning. If we would depend on this class and it changes we break our build scripts. But we can use a class from Ant that is already in Gradle's class path: org.apache.tools.ant.taskdefs.condition.Os. The class has several methods and constants to check the operating system name, version and architecture. The values are based on the Java system properties os.name, os.version and os.arch.

In the following example build script we use import static to include the Os class, so we can directly invoke the methods and refer to the constants in the Os class. We add some tasks that have a condition check with onlyIf so the task only runs when the condition in the closure is true. The task osInfo simply shows values from the Os class:

// File: build.gradle
import static org.apache.tools.ant.taskdefs.condition.Os.*

task os {
    description 'Run all conditional os tasks'
}

// Create 3 tasks that simply print
// the task name that is executed
// if the build scripts runs on the
// recognized operating system.
[FAMILY_WINDOWS, FAMILY_UNIX, FAMILY_MAC].each { osName ->

    // Create task.
    tasks.create(osName) {
        description "Run when OS is ${osName}"

        // Add condition to check operating system.
        onlyIf { isFamily(osName) }

        doLast {
            println "Execute task '${it.name}'"
        }
    }

    // Add task as dependency for the os task.
    os.dependsOn osName
}


task osInfo {
    description 'Show information about the operating system'
    doLast {
        println "Family:       ${OS_NAME}"
        println "Version:      ${OS_VERSION}"
        println "Architecture: ${OS_ARCH}"
    }
}

Let's run the os and osInfo tasks on MacOS:

$ gradle os osInfo
mac
Execute task 'mac'
:unix
Execute task 'unix'
:windows SKIPPED
:os
:osInfo
Family:       mac os x
Version:      10.12.3
Architecture: x86_64

BUILD SUCCESSFUL

Total time: 0.697 secs

Written with Gradle 3.3.