How to programmatically parse/retrieve user's parameters in Intellij project Gradle build file? Follow
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
Please sign in to leave a comment.
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
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?
Can I parse a custom block (other than "Ext") using GradleBuildModel API?
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.Thanks a lot Yann for this solution. I'll try this way.
Regards
Just as confirmation, it works well using PSI. thanks a lot.