Cydrick Trudel
Cydrick Trudel

Reputation: 10497

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?

Upvotes: 13

Views: 13149

Answers (2)

Akom
Akom

Reputation: 1631

I have a gradle project where a property set in settings.gradle is accessed from 3 places:

  • settings.gradle itself
  • build.gradle (including subprojects {} )
  • a gradle plugin in ./buildSrc

Accessing from settings.gradle and build.gradle:

gradle.ext.MY_PROPERTY_NAME

Accessing from a gradle plugin's apply() method:

(plugin is applied from subprojects {} closure)

project.rootProject.gradle.ext.MY_PROPERTY_NAME

This seems to work fine in Gradle 4.7 and Gradle 5.2

Upvotes: -1

Cydrick Trudel
Cydrick Trudel

Reputation: 10497

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.

Upvotes: 9

Related Questions