Gradle 使用 doLast 执行任务失败

Gradle exec task with doLast fails

我正在尝试 运行 仅当文件自上次构建以来已更新时才执行任务。我最初的尝试是这样的:

task generateLocalizedStrings(type:Exec) {
    ext.srcFile = file('../../../localization/language-files/en_US/wdmobilestringres.properties')
    ext.destDir = new File("src/main/res")
    inputs.file srcFile
    outputs.dir destDir

    doLast {
        println "Executing localization script"
        workingDir '../../../localization/'
        commandLine 'python', 'localizationScript.py'
    }
}

然而,这失败了 "execCommand == null!"

我找到了一个解决方法,但我真的更喜欢一个合适的解决方案。

task generateLocalizedStrings(type:Exec) {
    ext.srcFile = file('../../../localization/language-files/en_US/wdmobilestringres.properties')
    ext.destDir = new File("src/main/res")
    inputs.file srcFile
    outputs.dir destDir

    workingDir '../../../localization/'
    commandLine 'python', 'dummyScript.py'

    doLast {
        println "Executing localization script"
        workingDir '../../../localization/'
        commandLine 'python', 'localizationScript.py'
    }
}

您需要摆脱 doLast 块,而是在该块之外配置 workingDircommandLine。 (在 运行 之后配置任务为时已晚。)

一个选项是使任务成为通用任务并显式调用 exec dsl。例如。来自:

task("MyTask", type: Exec) {

    doLast {
        commandLine "your commandline"
    }
}

至此

task("MyTask") {

    doLast {
        exec {
            commandLine "your commandline"
        }
    }
}

也可以使用exec语法来执行doLast中的命令。它与 Exec 任务类型相同。例如,在 android 中,我需要访问 versionName 字段,该字段仅在同步后可用:

task fetchConfig {
    doLast {
        String versionName = android.defaultConfig.versionName
        String appName = projectDir.toPath().fileName
        exec {
            // Path to folder where your script is located
            workingDir = "$projectDir/../../scripts"
            // insert script name
            executable = new File(workingDir, 'fetch_config.sh')
            args = ["-b$appName", "-v$versionName", "--test", "etc"]
        }
    }
}