Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generic metric reporter for PMD
package net.sourceforge.pmd.lang.metrics.internal;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.metrics.LanguageMetricsProvider;
import net.sourceforge.pmd.lang.metrics.MetricKey;
import net.sourceforge.pmd.lang.rule.AbstractRule;
public class MetricReporter extends AbstractRule {
// don't forget to set the language in you ruleset xml
@Override
public void apply(List<? extends Node> nodes, RuleContext ctx) {
LanguageMetricsProvider<?, ?> pro = ctx.getLanguageVersion().getLanguageVersionHandler().getLanguageMetricsProvider();
nodes.stream()
.flatMap(n -> n.findDescendantsOfType(Node.class).stream())
// then you can parse the report
.forEach(n -> allMetrics(pro, n).forEach((k, v) -> addViolationWithMessage(ctx, n, k.name() + " : " + v)));
}
private Map<MetricKey<?>, Double> allMetrics(LanguageMetricsProvider<?, ?> provider, Node n) {
// the map may have some NaN values, when the metric is not supported
return provider.computeAllMetricsFor(n)
.entrySet()
.stream()
.filter(it -> !it.getValue().isNaN())
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
}
}
<ruleset name="TODO"
xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 https://pmd.sourceforge.io/ruleset_2_0_0.xsd">
<description>
TODO
</description>
<rule name="MetricReporter"
language="java"
class="net.sourceforge.pmd.lang.metrics.internal.MetricReporter">
<description>
Reports all available metrics
</description>
</rule>
</ruleset>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.