Read a build.gradle file from Java

1.4k views Asked by At

I want to analyze the build.gradle of my organization projects, primarily to create a sonarqube plugin that report the use of a dependency or the absence of a dependency.

The sonarqube plugin will be writed in Java and the input will be the .gradle files.

For example:


sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile "joda-time:joda-time:2.2"
    testCompile "junit:junit:4.12"
}

I want to get the dependency list for example in an List.class

Any idea?, how can I interpretate a .gradle file in Java?

1

There are 1 answers

0
Leo On
  1. call gradle from java. I've got the code from this answer How to run a gradle task from a java code?
  2. use dependecies task.

I recommend you to go this way so you do not have to handle the harsh task of keeping your code maintained with any version file change in gradle.

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;

    public class Main
    {
        private static String PATH_TO_GRADLE_PROJECT = "./";
        private static String GRADLEW_EXECUTABLE = "gradlew.bat";
        private static String BALNK = " ";
        private static String GRADLE_TASK = "dependencies";

        public static void main(String[] args)
        {
            String command = PATH_TO_GRADLE_PROJECT + GRADLEW_EXECUTABLE + BALNK + GRADLE_TASK;
            try
            {
                Runtime.getRuntime().exec(command);
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }