如何为Gradle任务的依赖项设置`onlyIf`?

时间:2013-09-04 21:51:14

标签: gradle

我希望在Gradle文件中获取任务的依赖关系列表,以便为它们添加onlyIf子句(这样可以关闭任务依赖关系的分支 - 与{{3相关] }})。怎么办呢?

例如:

def shouldPublish = {
    def propertyName = 'publish.dryrun'

    !project.hasProperty(propertyName) || project[propertyName] != 'true'
}

subprojects {
    publish {
        onlyIf shouldPublish
        // the following doesn't work;the gist is that publish's dependencies should be turned off, too
        dependencies {
            onlyIf shouldPublish
        }
    }
}

然后,在命令行上,可以:

gradlew -Ppublish.dryrun=true publish

1 个答案:

答案 0 :(得分:0)

以下作品:

def recursivelyApplyToTaskDependencies(Task parent, Closure closure) {
    closure(parent)

    parent.dependsOn.findAll { dependency ->
        dependency instanceof Task
    }.each { task ->
        recursivelyApplyToTaskDependencies(task, closure)
    }
}

def shouldPrune = { task ->
    def propertyName = "${task.name}.prune"

    project.hasProperty(propertyName) && project[propertyName] == 'true'
}

/*
 * Prune tasks if requested. Pruning means that the task and its dependencies aren't executed.
 *
 * Use of the `-x` command line option turns off the pruning capability.
 *
 * Usage:
 *   $ gradlew -Ppublish.prune=true publish # won't publish
 *   $ gradlew -Ppublish.prune=false publish # will publish
 *   $ gradlew -Dorg.gradle.project.publish.prune=true publish # won't publish
 *   $ gradlew -Dorg.gradle.project.publish.prune=false publish # will publish
 */
gradle.taskGraph.whenReady { taskGraph ->
    taskGraph.getAllTasks().each { task ->
        def pruned = shouldPrune(task)

        if (pruned) {
            recursivelyApplyToTaskDependencies(task) { p ->
                p.enabled = false
            }
        }
    }
}