Accessing conventions from within a task

(Jelmer Kuperus) #1

I developed a plugin that registers a convention and a bunch of tasks. The convention mostly holds file paths.

I also created a task that uses the file paths defined within the convention

I am now wondering if i should be accessing the convention directly from the task or whether i should be using the conventionMapping to set the values the task uses as defaults.

For many tasks i imagine, using the conventionMapping would be the best approach because that lets you reuse the task in a standalone way. However in this case the file paths not something you would override in any scenario and if i made every path a property of my task then using the task in a standalone fashion would be painful because if i understand correctly then each of the paths would have to be set manually by the caller.

Is it acceptable in that case to access the convention directly from the task ? Or is there some other clever technique i can use that allows these properties to be defaulted to a convention when used directly

(Peter Niederwieser) #2

Usually, convention objects (which have, for the most part, been replaced with extension objects) will be at a higher level of abstraction than the tasks. Otherwise, users could also configure the tasks directly with ‘tasks.withType(…) { … }’.

Whether to couple the tasks to the convention/extension object is a judgement call that you’ll have to make. As a general guideline, the more likely you are going to publish the plugin to third parties, the less likely you should have a tight coupling.

(Jelmer Kuperus) #3

Hey peter,

Thanks for the response. So I guess I should be using extension objects then ? Do you know of any resources that describe the differences between extensions and convention objects? Should you now always be using extension objects?

(Peter Niederwieser) #4

Start out by studying the “Writing Custom Plugins” chapter in the user guide. After that, have a look at some of the plugins in the Gradle codebase, for example the code quality plugins.

Unless you know exactly what you are doing and have a concrete reason to go with convention objects (and there aren’t many), you should always prefer extension objects. They are both easier to use and safer.