How do I create my own configuration block with a Gradle script plugin?

463 views Asked by At

Our company has a Gradle script plugin with a number of tasks in it. For instance, it includes the Jacoco afterEvaluate block from this answer:

def pathsToExclude = ["**/*Example*"]

jacocoTestReport {
    afterEvaluate {
        classDirectories = files(classDirectories.files.collect {
            fileTree(dir: it, exclude: pathsToExclude)
        })
    }
}

We would like to take that pathsToExclude variable and define that in our build.gradle file and have the rest of the logic in a script plugin (let's call it company-script-plugin.gradle. For instance:

apply from: http://example.com/company-script-plugin.gradle

companyConfiguration {
    pathsToExclude = ["**/*Example*"]
}

Our initial thought was to add a task in the build script so that we could get a companyConfiguration

task companyConfiguration {
    ext.pathsToExclude = []
}

However, we think that this is a hacky workaround because running the task doesn't do anything. What is the proper way to create my own configuration block?

We'd like it to be as simple as possible, and to be a script plugin (rather than binary plugin) if possible.

1

There are 1 answers

2
Opal On

Here you've an example how it can be done:

apply plugin: CompanyPlugin

companyConfiguration {
  pathsToExclude = ['a', 'b', 'c']
}

class CompanyPlugin implements Plugin<Project> {

  void apply(Project p) {
    println "Plugin ${getClass().simpleName} applied"
    p.extensions.create('companyConfiguration', CompanyConfigurationExtension, p)
  }

}

class CompanyConfigurationExtension {
  List<String> pathsToExclude

  CompanyConfigurationExtension(Project p) {
  }

}

task printCompanyConfiguration {
  doLast {
    println "Path to exclide $companyConfiguration.pathsToExclude"
  }
}

Also, please have a look at the docs.