Creating a task that runs before all other tasks in gradle

前端 未结 3 1833
不思量自难忘°
不思量自难忘° 2021-02-14 21:09

I need to create an initialize task that will run before all other task when I execute it.

task A {
    println \"Task A\"
}

task initializer {
   println \"ini         


        
3条回答
  •  一向
    一向 (楼主)
    2021-02-14 21:37

    The previously suggested solution with dependsOn works fine, but I don't like about it that it changes and clutters the task dependencies. The first solution coming to my mind is using Gradle Initialization Scripts. They are really cool. But, the usage is a bit tedious: currently there is no way to have a default project-local Gradle init script. You have to either explicitly specify the script(s) on command line, or place them in USER_HOME/GRADLE_HOME.

    So another solution (already briefliy mentioned by @lance-java) which can be used to run some initialization, like a init task/script, is "build listeners". Depending on how early/late the initialization code should run, I use one of these two:

    gradle.afterProject {
        println '=== initialized in afterProject'
    }
    

    or

    gradle.taskGraph.whenReady {
        println '=== initialized in taskGraph.whenReady'
    }
    

    Here the docs of the Gradle interface and of BuildListener.

    Note that some of the events occur very early, and you probably can't use them because of that, like e.g. beforeProject and buildStarted (explanations here and there).

提交回复
热议问题