每个项目模块的Gradle可重用自定义任务

时间:2019-06-11 07:50:55

标签: gradle build.gradle

如何定义可用于模块的自定义任务?就我而言,我想使用一个Exec任务来运行一个脚本,该脚本带有特定于子项目的commandLine自变量。

例如:

脚本

#!/usr/bin/env sh
echo "$@"

build.gradle

task customExecTask(type: Exec) {
  if (project.name == "a") {
    commandLine './script', "Project 'a'"
  } else if (project.name == "b") {
    commandLine './script', "Project 'b'"
  }
}

project('a') {
  build.dependsOn ':customExecTask'
}

project('b') {
  build.dependsOn ':customExecTask'
}

编辑

或者类似这样的东西:

task customExecTask(type: Exec) {
  def dynamicVariable = ""
  commandLine './script', dynamicVariable
}

project('a') {
  task(':customExecTask').dynamicVariable = "Project 'a'"
  build.dependsOn ':customExecTask'
}

project('b') {
  task(':customExecTask').dynamicVariable = "Project 'b'"
  build.dependsOn ':customExecTask'
}

预期结果:

$ gradle :a:build
Project 'a'

$ gradle :b:build
Project 'b'

2 个答案:

答案 0 :(得分:0)

请参阅Using Gradle Plugins上的文档。

根据此topic,您可以将任务放置在单独的gradle文件mytask.gradle中,并放入添加到build.gradle的每个模块中:

apply from: "${rootDir}/pathtomycustomgradlefile/mytask.gradle"

如果您需要更多逻辑来决定应用哪个逻辑,则可以检查主题Applying plugins to subprojects

答案 1 :(得分:0)

我找到了解决方案。对于我的第一个示例,我只想执行根项目目录中的脚本,并为每个子项目指定特定的参数。为了使任务正常运行,您必须在subprojects闭包中定义任务。以下是单个build.gradle设置的完整工作示例。

目录结构:

├─ a                 # Module 'a' folder
├─ b                 # Module 'b' folder
├─ build.gradle      # Root project build file
├─ script            # Executable bash script
└─ **/               # Other files and folder

脚本

#!/usr/bin/env sh
echo "$@"

build.gradle

subprojects { // Define the task here
  task customExecTask(type: Exec) {
    // Change the directory where the script resides
    workingDir = rootDir
    // Conditional arguments depending on each project modules.
    // We'll use the property 'project.name' to determine the
    // current project this task is running from
    def customArgs = project.name == 'a' ? "Hello" : "World"
    // Then execute the script with customArgs variable
    commandLine './script', customArgs
    // Or in Windows: commandLine 'cmd', '/c', 'script.bat'
  }
}

project('a') {
  build.dependsOn 'customExecTask'
}

project('b') {
  build.dependsOn 'customExecTask'
}

控制台结果:

$ gradle build

> Task :a:execute
Hello

> Task :b:execute
World