What is the correct way to define tasks in the Gradle plugin?

I am trying to create my first Gradle plugin.
1. Add an extension for the properties: project.extensions.create("abc", AbcExtension)
2. Define the copy task. When I define a task as follows

 project.task("abcTask", type: Copy) { from project.abc.fromPath into project.abc.intoPath } 

project.abc.fromPath is equal to the value of AbcExtension.fromPath - it does not read the values ​​from build.gradle .
When I define a task as follows

 project.task("abcTask", type: Copy) << { from project.abc.fromPath into project.abc.intoPath } 

it always prints UP-TO-DATE and does not run the task.

Pls explains this behavior and tells me what is the correct way to define tasks in Gradle plugins (with type and dependsOn functionallity)

+4
source share
1 answer

Plugins should defer every reading of the value of the mutable assembly model (i.e. everything that can be installed from the assembly script), at least until the end of the configuration phase. There are several ways to achieve this. Among them:

  • Using the Gradle API, which accepts closures as values ​​(e.g. Copy.from )
  • Using callbacks like project.afterEvaluate {} or gradle.projectsEvaluated {}
  • Using the legend mapping mechanism (note that this is not considered a public function)

Choosing the best option for working at hand requires some experience. (This can help learn some of the plugins in Gradle codebase .) In your case, I can do the following:

 project.task("abcTask", type: Copy) { from { project.abc.fromPath } into { project.abc.intoPath } } 

Your version of << does not work because it configures the Copy task too late. Generally speaking, the entire configuration should be performed at the configuration phase, and not at the execution stage. For more information on the phases of the Gradle build, see the Gradle User Guide .

+11
source

All Articles