How can you use an init script to specify a repo/dependency for a plugin JAR, but allow version to be configured in build's root project?

This question came from Luke’s Enterprise Gradle webinar on 7/31. I think I followed his response during the talk, but wanted to get it documented in the forum just in case.

Currently every individual build script we have migrated to Gradle has a boilerplate block at the top to declare the repositories like below:

buildscript {
  repositories { maven { url 'http://....' } }
  dependencies { classpath 'corp:plugins:1.3.4' }
}

Not only is this in every build, but in every project of the build: very much a violation of DRY.

I would like to have this integrated into an init script, but still want the version of the plugin to be configurable in each build’s root project.

Perfect! We wouldn’t want to put the apply statement in the init script, so no issues on that part.

A year later, is there no solution to this yet? not sure where it lands on the road map but this type of functionality is super useful when it works as expected.

This is how you could do it.

In your ‘init.gradle’:

class OurPlugins {
    def buildscript
      OurPlugins(buildscript) {
        this.buildscript = buildscript
        buildscript.repositories {
            mavenCentral()
        }
    }
          void jsPlugin(String version) {
        buildscript.dependencies {
            classpath "com.eriwen:gradle-js-plugin:$version"
        }
    }
}
  allprojects {
    extensions.create('ourPlugins', OurPlugins, buildscript)
}

Then in your ‘build.gradle’ (assuming you want to apply the plugin to all children):

buildscript {
    allprojects {
        ourPlugins.jsPlugin "1.0"
    }
}
  allprojects {
    apply plugin: "js"
}

The application has to be outside of the ‘buildscript’ block right now, and outside of the init script because of GRADLE-2407. When that is fixed, you could make it a little more concise.