Christian Quast Christian Quast - 4 months ago 12
Groovy Question

Custom standalone gradle Plugins aren't as powerful as usual build.gradle code?

Sorry if this seems to be a foolish question. But I'm a beginner in Java and Gradle and I am really having this problems with the 'Gradle Docs' sometimes.

I just want to find an easy way to reuse code from my project's

build.gradle
file. So packing this code into a plugin that is uploaded and versioned in my company repo seemed to be ideal. But those standalone plugins are
java/groovy
projects/programs
with different syntax than the gradle DSL. So they don't facilitate the same possibilities and closures as in a gradle.build file, right?

For example if i wanted a repositories closure to be reusable, looking like this:

repositories {
maven {
url project.Repo_GP_Internal
credentials {
username project.Repo_GP_User
}
}
}


or the uploadArchives closure:

uploadArchives {
repositories {
mavenDeployer {
repository(url: Repo_Upload_Internal){
authentication(userName: project.Repo_Upload_User, password: project.Repo_Upload_Pass)
}
snapshotRepository(url: Repo_Upload_Snapshot){
authentication(userName: project.Repo_Upload_User, password: project.Repo_Upload_Pass)
}
}
}
}


Can I pack this in any way into a plugin which can be uploaded to my repo as a jar? As you see it's about code from the configuration phase.

Thank you in advance.

Answer

You definitely can use every feature available to you in build.gradle from plugin as well.

The build.gradle file is essentially just a groovy script executed with project object set as a delegate and most magic words you use in it (like task) are just methods of the Project class. The most significant difference is that in your custom plugin or task you have to interact with project explicitly.

Something like this should do the trick:

class MyPlugin implements Plugin<Project> {
    void apply(Project project) {
        project.repositories {
            maven {
                url project.Repo_GP_Internal
                credentials {
                    username project.Repo_GP_User
                }
            }
        }
    }
}

For methods available inside the repositories closure, see documentation for RepositoryHandler

Of course, there's still the question of how your project will be accessing your plugin. For example, it may be retrieving it from a maven repository, in which case you would need to define buildscript { repositories { with that maven repository parameters explicitly in each project.