Hi,
Using the SonarQube API 6.7.3 is there any way to determine if an InputModule is the root module (project) of a multi-module system?
In a Sensor implementation in the execute method I retrieve the InputModule from the SensorContext (parameter in the execute method).
Example:
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
public final class MySensor implements Sensor
{
@Override
public void describe(final SensorDescriptor descriptor)
{
descriptor.name("MyPlugin");
}
@Override
public void execute(final SensorContext context)
{
final InputModule inputModule = context.module();
//TODO is root module (project)?
}
}
Thanks in advance for any help.
Regards
Dietmar Menges
Hi Dietmar,
There is a way using ProjectDefinition, even if this is not very easy.
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
public final class MySensor implements Sensor {
private final ProjectDefinition def;
public MySensor(ProjectDefinition def) {
this.def = def;
}
@Override
public void describe(final SensorDescriptor descriptor) {
descriptor.name("MyPlugin");
}
@Override
public void execute(final SensorContext context) {
final InputModule inputModule = context.module();
if (isRootModule()) {
// ...
}
}
private boolean isRootModule() {
return def.getParent() == null;
}
}
Another option depending on your use case is to declare your Sensor as “global”. It will run only once for the entire project.
import org.sonar.api.batch.sensor.Sensor;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.SensorDescriptor;
public final class MySensor implements Sensor {
@Override
public void describe(final SensorDescriptor descriptor) {
descriptor
.name("MyPlugin")
.global();
}
@Override
public void execute(final SensorContext context) {
final InputModule rootModule = context.module();
// Only run on the root module
}
}
Good luck
Hi Julien,
That is very helpful. Thank you very much.
Regards
Dietmar