Minimizing copy and paste build.gradle code between projects

I have a monolith repo that I’m breaking up into > 6 repos. I want to enable a simple set of plugins like Checkstyle, FindBugs, and PMD between all repos; and share the same configuration.

I’m pretty new to Gradle so I’m not 100% of the “best” way to do this. I thought maybe a plugin that configured other plugins would be the “right” way but I can’t seem to find any supporting documentation on how to do this so it makes me think this is an anti-pattern.

What would be the right way to ensure that these 6 new repos all share the same Checkstyle, FindBugs, and PMD plugins?

A plugin sounds like a reasonable idea to me. It would look something like:

class MyPlugin implements Plugin<Project> {
   void apply(Project project) {
      project.with {
         apply plugin: 'checkstyle'
         apply plugin: 'pmd' 
         apply plugin: 'findbugs' 

         tasks.withType(Checkstyle) {
             reports {
                 xml.enabled false
                 html.enabled true 
             }
         }
      } 
   } 
} 

Note1: FindBugs plugin is not maintained and is deprecated, you’re probably better using the SpotBugs plugin.

Note2: If you need to apply 3rd party plugins, you’ll need to add the dependencies to your plugin’s build.gradle

Another option is to host a gradle file at a publicly available URL. You could then do

apply from: 'http://path/to/myscript.gradle'

Note: Its best to include a version number in the path so you can manage changes over time.

Thanks for the info, that’s very helpful.

Just as a followup question: is either one considered “best practice”? We do have an internal Artifactory instance where we could house either the plugin jar or the gradle script. I, personally, tend to favor the plug-in as it seems more “natural” to gradle as that’s how other plugins are configured.

I’d probably favour a plugin too which is released and versioned same as other dependencies. If you happen to have shared resources as part of your plugin (eg checkstyle.xml) these could be packed inside the jar and accessed via the classloader

Thanks. I’ve opted to use the plugin, and following your input, I’m including all static resource (xml files, style sheets … etc) as part of the jar so it can be references within the classpath.

I’ve been using the kordamp plugins for my project, because I’m generally unsure of how Gradle works in general.