Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you support a Gradle Exec task for both Mac and PC?

Is there a way to be able to execute a task on both Windows and Mac if the commands take a different form? For example:

task stopTomcat(type:Exec) {

    // use this command line if on Windows
    commandLine 'cmd', '/c', 'stop.cmd'

    // use the command line if on Mac
    commandLine './stop.sh'
}

How would you do this in Gradle?

like image 360
Ken Avatar asked Dec 10 '14 16:12

Ken


People also ask

How do I run the Gradle task command line in Windows?

To run a Gradle command, open a command window on the project folder and enter the Gradle command. Gradle commands look like this: On Windows: gradlew <task1> <task2> … ​ e.g. gradlew clean allTests.

Does Gradle run all tasks?

You can execute multiple tasks from a single build file. Gradle can handle the build file using gradle command. This command will compile each task in such an order that they are listed and execute each task along with the dependencies using different options.

Where are Gradle tasks defined?

You define a Gradle task inside the Gradle build script. You can define the task pretty much anywhere in the build script. A task definition consists of the keyword task and then the name of the task, like this: task myTask. This line defines a task named myTask .


3 Answers

You can conditionally set the commandLine property based on the value of a system property.

if (System.getProperty('os.name').toLowerCase(Locale.ROOT).contains('windows')) {
    commandLine 'cmd', '/c', 'stop.cmd'
} else {
    commandLine './stop.sh'
}
like image 111
Mark Vieira Avatar answered Oct 15 '22 10:10

Mark Vieira


If the script or executable were the same on windows and linux then you'd be able to do the following so that you only have to define the arguments once by calling a function like so:

       import org.apache.tools.ant.taskdefs.condition.Os       

       task executeCommand(type: Exec) {    
            commandLine osAdaptiveCommand('aws', 'ecr', 'get-login', '--no-include-email')
       }

       private static Iterable<String> osAdaptiveCommand(String... commands) {
            def newCommands = []
            if (Os.isFamily(Os.FAMILY_WINDOWS)) {
                newCommands = ['cmd', '/c']
            }

            newCommands.addAll(commands)
            return newCommands
       }
like image 39
bitrock Avatar answered Oct 15 '22 10:10

bitrock


I referred to here. https://stackoverflow.com/a/31443955/1932017

import org.gradle.nativeplatform.platform.internal.DefaultNativePlatform

task stopTomcat(type:Exec) {
    if (DefaultNativePlatform.currentOperatingSystem.isWindows()) {
        // use this command line if on Windows
        commandLine 'cmd', '/c', 'stop.cmd'
    } else {
        // use the command line if on Mac
        commandLine './stop.sh'
    }
}
like image 42
YujiSoftware Avatar answered Oct 15 '22 08:10

YujiSoftware