您如何支持 Mac 和 PC 的 Gradle Exec 任务



如果命令采用不同的形式,有没有办法能够在Windows和Mac上执行任务?例如:

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'
}

你会如何在 Gradle 中做到这一点?

可以根据系统属性的值有条件地设置 commandLine 属性。

if (System.getProperty('os.name').toLowerCase(Locale.ROOT).contains('windows')) {
    commandLine 'cmd', '/c', 'stop.cmd'
} else {
    commandLine './stop.sh'
}

如果脚本或可执行文件在Windows和Linux上是相同的,那么您将能够执行以下操作,以便您只需通过调用这样的函数来定义一次参数:

       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
       }

我在这里提到。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'
    }
}

最新更新