Do we have any option to read the contents of the build.gradle file in a java program. I was able to do something similar in maven using the below code. Now, I'm looking at options to do the same in gradle. I tried using Gradle-tooling-api as explained below, but getting some errors (not sure if I'm following the right approach).
reading pom.xml using MavenXpp3Reader
```FileReader fileReader;
try {
fileReader = new FileReader(destPath);
} catch (FileNotFoundException fileNotFoundException) {
fileNotFoundException.printStackTrace();
}
MavenXpp3Reader reader = new MavenXpp3Reader();
Model pomModel = reader.read(fileReader);
//close the file reader
fileReader.close();
```
Tried to leverage gradle-tooling-api as below, but got the below error.
public class ToolingApiCustomModelPlugin implements Plugin<Project> {
private final ToolingModelBuilderRegistry registry;
@Inject
public ToolingApiCustomModelPlugin(ToolingModelBuilderRegistry registry) {
this.registry = registry;
}
@Override
public void apply(Project project) {
registry.register(new CustomToolingModelBuilder());
}
private static class CustomToolingModelBuilder implements ToolingModelBuilder {
@Override
public boolean canBuild(String modelName) {
return modelName.equals(CustomModel.class.getName());
}
@Override
public Object buildAll(String modelName, Project project) {
List<String> pluginClassNames = new ArrayList<String>();
for(Plugin plugin : project.getPlugins()) {
pluginClassNames.add(plugin.getClass().getName());
}
return new DefaultModel(pluginClassNames);
}
}
}
public static void main(String[] args) {
GradleConnector connector = GradleConnector.newConnector();
connector.forProjectDirectory(new File("./sample"));
ProjectConnection connection = null;
try {
connection = connector.connect();
ModelBuilder<CustomModel> customModelBuilder = connection.model(CustomModel.class);
//customModelBuilder.withArguments("--init-script", "init.gradle");
CustomModel model = customModelBuilder.get();
}
Exception in thread "main" org.gradle.tooling.UnknownModelException: No model of type 'CustomModel' is available in this build.
Caused by: org.gradle.tooling.provider.model.UnknownModelException: No builders are available to build a model of type 'org.gradle.sample.toolingapi.CustomModel'.