How to parse file?

(Lovett Li) #1

I want to parse 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.

(Lovett Li) #2

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

(Lovett Li) #3

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

public class ParseGradleFileVisitor extends CodeVisitorSupport
    public void visitMethodCallExpression( MethodCallExpression call )
        //your logic code

    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.

(hg) #4

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 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.

(Lovett Li) #5

Hey hg_fs2002
You can see follow link that will show you how to invoke my custom gradle parser.

Following links are core of my custom gradle parser it is intend to parse a file and get available dependence block. Hope it can help you.

(Marc) #6

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