Coincidentally, something came up I wanted to blog about, and it turns out it’s a follow up to the last blog post I wrote 9 months ago.
I’ve been increasingly unhappy with using “apply from” to apply a script plugin from a hard coded location. It’s no use if you’re offline, or not on the right VPN to access the file, or whatever. What I didn’t realise is that I could do apply all the same configuration defaults from a binary plugin. Then you get proper dependency management like you would with a Maven parent pom.
Here’s the code for the Plugin, which is just a standard gradle plugin
import org.gradle.api.Project
import org.gradle.api.Plugin
import org.apache.log4j.Logger
import org.gradle.api.GradleException
public final class CommonConfigPlugin implements Plugin<Project>{
@Override
void apply(Project project) {
addDependencies(project)
applyPlugins(project)
configureReleasePlugin(project)
}
private void configureReleasePlugin(Project project) {
if (!project.parent) {
project.createReleaseTag.dependsOn { project.allprojects.uploadArchives }
}
//do this for all projects
project.uploadArchives {
... config here ...
}
}
private void addDependencies(Project project) {
project.afterEvaluate {
project.dependencies.add("testCompile", "junit:junit:4.11")
project.dependencies.add("compile", "log4j:log4j:1.2.14")
}
}
private void applyPlugins(Project project) {
project.configure(project){
apply plugin: 'java'
apply plugin: 'maven'
}
//apply these to parent project only
if (!project.parent) {
project.configure(project){
apply plugin: 'sonar-runner'
apply plugin: 'release'
}
}
}
}
Then in the main build.gradle file for any project, I add the jar as a dependency and apply the plugin.
allprojects {
repositories {
mavenLocal()
maven { url "http://my.repo"}
}
apply plugin: "my-common-config"
}
buildscript {
repositories {
mavenLocal()
maven { url "http://my.repo"}
}
dependencies {
classpath 'uk.co.anorakgirl.gradle:my-common-config-plugin:1.0.0'
}
}
Any dependencies which the plugin has end up as dependencies in the buildscript of the project, meaning I don’t have to repeat the dependency on the release plugin, because my common config plugin already depends on it.
I’m going to put more in this common-config-plugin.