How to programmatically parse/retrieve user's parameters in Intellij project Gradle build file?

Answered

Hello all,

I need to retrieve some user specific parameters from Gradle build file in an Intellij project (build.gradle.kts)
Here a "build.gradle.kts" file content example I need to parse:
...
cutomParameters {
param1.set("any value")
sub_parameters1 {
sub_parameter1_1.set("foo")
}
subParameters2 {
subParameter21("foo")
subParameter22 {
subParameter221.set("foo")
}
}
}
...

I tried some code like this:
val connection: ProjectConnection =
GradleConnector.newConnector().forProjectDirectory(File(projectPath)).connect()

val model = connection.model(GradleBuild::class.java)

I can get the gradle build file using "model.get().buildFile" but how to retrieve the custom parameters described in the previous example?

Any help would be appreciated.

Thanks a lot in advance
Chris

5 comments
Comment actions Permalink

You can use (still experimental) API from Gradle plugin to access information from build file directly from within the IDE:

com.android.tools.idea.gradle.dsl.api.ProjectBuildModel#getModuleBuildModel(com.intellij.openapi.module.Module) (or File/Project) to obtain com.android.tools.idea.gradle.dsl.api.GradleBuildModel which contains all information

0
Comment actions Permalink

Thanks a lot Yann,

I already used this API, but it seems that only the "ext" block is accessible and parameters inside this "ext" block are in a flatten way (no hierarchical parameters, unlike described in my previous example). Am I right?

0
Comment actions Permalink

Can I parse a custom block (other than "Ext") using GradleBuildModel API?

0
Comment actions Permalink

For custom blocks, one can try to use GradleBuildModel#getPsiFile and then use Gradle PSI or Kotlin PSI (based on returned psi file type) for further parsing.

0
Comment actions Permalink

Thanks a lot Yann for this solution. I'll try this way.

Regards

0

Please sign in to leave a comment.