从插件摇篮任务不上“构建”运行,但在“清洁”是否运行

问题描述 投票:4回答:1

我们有这需要一定的摇篮插件任务运行我们所建立的APK之前的Android项目。 (该插件是由我们写的)

我们希望每一个构建之前自动运行任务。

如果我们使用过时task.execute()那么我们得到的,这将是不可用的版本开始,5.0或类似的东西警告。

如果我们使用dependsOn推荐,然后testTask1是不能建立之前,但干净后只。 (所有的评论下面解释)

我一直在gradle这个文档,和许多其他SO线程,但我还没有找到一个解决方案。

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {

    repositories {
        flatDir { dirs 'libs' }
        jcenter()
        google()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:3.1.3"

        // our platform-tools plugin, in charge of some gradle tasks
        classpath 'sofakingforevre:test-plugin:1.0-SNAPSHOT'
    }
}


apply plugin: 'test-plugin'


allprojects {
    repositories {
        jcenter()
        google()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


// OPTION 1 - USING EXECUTE()

// this task works as expected when calling "clean", but also when calling "assemble".
// the problem here is that the "execute" method has been deprecated, and we want to prepare for Gradle 5.0

// CLEAN - testTask1 is called :)
// BUILD - testTask1 is called :)
// DEPRECATION WARNING :(
task buildPlatformExecute {

    println("executing")

    // this task is created by the plugin
    tasks.getByName("testTask1").execute()


}

clean.dependsOn buildPlatformExecute

// OPTION 2 - USING DEPENDSON()

// this tasks works as expected when calling "clean", but DOES NOT WORK when calling "assemble".
// If we call we call assemble, the "executing" text does print, but "testTask1" would not run.

// CLEAN - testTask1 is called :)
// BUILD - testTask1 is NOT CALLED :(
task buildPlatformDependency {

    println("executing")

    // this task is created by the plugin
    dependsOn 'testTask1'
}

clean.dependsOn buildPlatformDependency
android gradle android-gradle build.gradle gradle-plugin
1个回答
2
投票

与OPTION 1解决的问题

  • 您正在使用过时的task.execute() API(你已经意识到这一点)
  • 你混合配置和执行阶段(一个共同的摇篮错误...):

因为你没有在tasks.getByName("testTask1").execute()任务doLast {}块的doFirst {}包裹buildPlatformExecute:在testTask1任务就一定会执行,不管任务中,您将调用。你甚至都不需要创建clean任务和自定义任务之间的依赖关系(例如:尝试执行简单的“帮助”任务with./gradlew help你将看到的是也执行该testTask1:这肯定不是你想要的)

点击此处了解详情:https://docs.gradle.org/current/userguide/build_lifecycle.html

问题与解决方案OPTION2

你创造了clean任务andbuildPlatformDependency任务之间的依赖关系:

  • 执行clean任务时,如预期testTask1任务将被执行,但
  • build(或assemble)任务和clean任务之间不存在相关性:这就是为什么当你执行任务build,不执行clean任务(所以testTask1不会被触发)

最好的办法是钩你自定义任务testTask1在你的项目构建生命周期中的正确位置,使用Task.dependsOn API。 “正确”的位置取决于你的任务是负责在构建过程:例如,如果你的工作需要进行前assemble任务执行,只需创建依赖assemble.dependsOn testTask1

© www.soinside.com 2019 - 2024. All rights reserved.