Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access property from settings.gradle in Gradle plugin

I am in the process of building a custom Gradle plugin using the following guide. I want to define a property in the settings.gradle file and read it in the plugin class, but every attempt failed so far.

Here is the error I am getting:

Could not find property 'MyProperty' on root Project 'MyProject'

Here is my settings.gradle file:

gradle.ext.MyProperty = "The Value"

and here is the file containing my plugin:

package myplugin.gradle

import org.gradle.api.Project
import org.gradle.api.Plugin

class FirstPlugin implements Plugin<Project> {
    void apply(Project project) {
        project.task('myTask') << {
            def instance = project.MyProperty
            println "VALUE : " + instance
        }
    }
}

I can access MyProperty if I put project.ext.set("MyProperty", "Property Value") in build.gradle, but I can't find a way to set it in the settings.gradle file.

I guess one way to fix this issue would be to read the content of settings.gradle in build.gradle and send it to the plugin using project.ext.set(...), but is there a more direct way?

like image 640
GammaOmega Avatar asked Sep 14 '15 12:09

GammaOmega


1 Answers

Apparently, the way to go (which is better anyways) is to use an extension object. This extension object allows to send data from the build.gradle file to the plugin. The build.gradle file reads the content of the variable in the settings.gradle file and puts it in the extension object.

In the file containing the plugin:

package myplugin.gradle

import org.gradle.api.Project
import org.gradle.api.Plugin

class MyExtension {
    String myProperty
}

class FirstPlugin implements Plugin<Project> {
    void apply(Project project) {
        project.extensions.create('myExtensionName', MyExtension)
        project.task('myTask') << {
            def instance = project.myExtensionName.myProperty
            println "VALUE : " + instance
        }
    }
}

In the build.gradle file:

apply plugin: 'myPluginName'
...

myExtensionName {
    myProperty = gradle.ext.myPropertyInSettings
}

And finally, in the settings.gradle file :

gradle.ext.myPropertyInSettings = "The Value"

Also, I recommend this tutorial instead of the one provided by Gradle.

like image 180
GammaOmega Avatar answered Oct 11 '22 17:10

GammaOmega