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?
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.
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.
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 .
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'
}
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
}
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'
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With