'How can I apply the Gradle Versions Plugin from an initscript?

I'm trying to set things up so that I can use the Gradle Versions Plugin without having to add it to all of my build.gradle files.

Based on this answer to a related question, I tried creating a file ~/.gradle/init.d/50-ben-manes-versions.gradle:

initscript {
    repositories {
       jcenter()
    }

    dependencies {
        classpath 'com.github.ben-manes:gradle-versions-plugin:0.17.0'
    }
}

allprojects {
    apply plugin: com.github.ben-manes.versions
}

If I then try to invoke ./gradlew dependencyUpdates in my repo, I get:

FAILURE: Build failed with an exception.

* Where:
Initialization script '~/.gradle/init.d/50-ben-manes-versions.gradle' line: 13

* What went wrong:
Could not get unknown property 'com' for root project 'project-name' of type org.gradle.api.Project.

That answer said to not use quotes around the plugin name, but since that didn't work I tried adding quotes (ie: apply plugin: 'com.github.ben-manes.versions'). With that I get:

FAILURE: Build failed with an exception.

* Where:
Initialization script '~/.gradle/init.d/50-ben-manes-versions.gradle' line: 13

* What went wrong:
Plugin with id 'com.github.ben-manes.versions' not found.

Is there any way to apply the Gradle Versions Plugin from an initscript?

I am using Gradle 4.3.1, by the way.



Solution 1:[1]

I am using the solution from @mkobit for a while now. It works great, however it does not support the case when the project you are working on already has the versions plugin applied.

I am using a slightly modified version of the script now that does not apply the plugin if it already exists (in Groovy DSL):

initscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'com.github.ben-manes:gradle-versions-plugin:0.42.0'
    }
}

allprojects {
    afterEvaluate { project ->
        if (project.parent == null) {
            def hasPlugin = project.plugins.any {
                it.class.name == "com.github.benmanes.gradle.versions.VersionsPlugin"
            }

            if (!hasPlugin) {
                project.apply plugin: com.github.benmanes.gradle.versions.VersionsPlugin
            }
        }
    }
}

EDIT: There is now an API to ask if a plugin has been applied. Example in Kotlin DSL

initscript {
    repositories {
        gradlePluginPortal()
    }

    dependencies {
        classpath("com.github.ben-manes:gradle-versions-plugin:0.42.0")
    }
}
// don't use rootProject as it may not be ready
allprojects {
    afterEvaluate {
        if (parent == null) {
            if (!plugins.hasPlugin("com.github.ben-manes.versions")) {
                apply<com.github.benmanes.gradle.versions.VersionsPlugin>()
            }
        }
    }
}

Tested with Gradle 7.4

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Brice