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

如何为Gradle任务的依赖项设置“onlyIf”?,gradle,Gradle,我希望在一个Gradle文件中获得一个任务依赖项列表,以便在其中添加一个onlyIf子句(这样可以关闭任务依赖项的分支——与相关)。如何做到这一点 例如: def shouldPublish = { def propertyName = 'publish.dryrun' !project.hasProperty(propertyName) || project[propertyName] != 'true' } subprojects { publish {

我希望在一个Gradle文件中获得一个任务依赖项列表,以便在其中添加一个
onlyIf
子句(这样可以关闭任务依赖项的分支——与相关)。如何做到这一点

例如:

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
以下工作:

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

你想干什么?你能举个例子吗@Ethan,我已经添加了更多的细节。使用
--dry run
怎么样?除此之外,已经解释了所有的可能性。@PeterNiederwieser,这可能是一种可能性。我正试图在詹金斯做到这一点。如果Gradle任务能够在options字段中计算环境变量,那么事情应该会很顺利。@PeterNiederwieser,为什么上面的
依赖项
块不起作用?