How to parse gradle.build file?

I want to parse gradle.build file use AST and get dependence block and find out line number. I used GroovyLexer and GroovyRecognizer can parse groovy source code but it’s not work to parse grade build script.I know gradle use groovy.
Does anybody know how to parse it ? I really appreciate.

1 Like

CodeVisitorSupport is good solution that you can parse every block in gradle configuration file.

I post some code so that help people who encounter this problem.

public class ParseGradleFileVisitor extends CodeVisitorSupport
{
   @Override
    public void visitMethodCallExpression( MethodCallExpression call )
    {
        //your logic code
    }

  @Override
    public void visitArgumentlistExpression( ArgumentListExpression ale )
    {
       //your logic code
    }
}

So this CodeVisitorSupport has many method that you can use to get object from gradle configuration file.
For example dependences{ } in gradle file will be looked as a method named dependences. You can get this MethodCallExpression object then get argument list like group, name , version .etc.

Hope it can help you.

@lovettli
Thanks for the post. I am trying to do what you suggested and the problem I have is that I am not sure how I should call the ParseGradleFileVisitor. I assume I should somehow get the translation unit or AST of the gradle.build file and then call the visitor. However, I am not able to successfully do that. I am wondering if you can help me regarding that.

Hey hg_fs2002
You can see follow link that will show you how to invoke my custom gradle parser.
https://github.com/lovettli/liferay-ide/blob/master/tools/tests/com.liferay.ide.gradle.core.tests/src/com/liferay/ide/gradle/core/tests/GradleParseTests.java

Following links are core of my custom gradle parser it is intend to parse a gradle.build file and get available dependence block. Hope it can help you.
https://github.com/lovettli/liferay-ide/blob/master/tools/plugins/com.liferay.ide.gradle.core/src/com/liferay/ide/gradle/core/parser/GradleDependencyUpdater.java

https://github.com/lovettli/liferay-ide/blob/master/tools/plugins/com.liferay.ide.gradle.core/src/com/liferay/ide/gradle/core/parser/FindDependenciesVisitor.java

Hi everybody

I use a similar approach but I get the following error for complicated gradle scripts with import statements that can’t be resolved:
Exception in thread “main” org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script42328008517924.groovy: 14: unable to resolve class

Did anyone encounter a similar issue? I’m not quite sure how to proceed.

Best regards
Marc