Skip to content

Instantly share code, notes, and snippets.

@mikybars
Last active September 14, 2021 10:59
Show Gist options
  • Select an option

  • Save mikybars/3063bf33edb8bc835c9569175d7f569d to your computer and use it in GitHub Desktop.

Select an option

Save mikybars/3063bf33edb8bc835c9569175d7f569d to your computer and use it in GitHub Desktop.
[Custom Java inside Maven] Maven Enforcer plugin lets you define custom conditions in a lightweight Java. https://maven.apache.org/enforcer/enforcer-rules/evaluateBeanshell.html #maven #java
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<executions>
<execution>
<id>check-coverage</id>
<phase>install</phase>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<fail>true</fail>
<rules>
<evaluateBeanshell>
<message>Code coverage check failed (&lt; ${min.coverage}%)</message>
<condition>
import java.io.BufferedReader;
import java.io.FileReader;
import java.text.DecimalFormat;
if (System.getenv("bamboo_build_working_directory") != null) {
print("Skipping coverage check: running on CI");
return true;
}
try {
minCoverage = Float.parseFloat("${min.coverage}");
} catch (NumberFormatException e) {
print("Skipping coverage check: no limit defined or bad format (min.coverage)");
return true;
}
coverageOk = true;
jacocoCsv = "${project.reporting.outputDirectory}/jacoco-aggregate/jacoco.csv";
input = null;
try {
missed = covered = 0;
input = new BufferedReader(new FileReader(jacocoCsv));
input.readLine(); // skip header line
while ((line = input.readLine()) != null) {
values = line.split(",");
missed += Integer.parseInt(values[3]);
covered += Integer.parseInt(values[4]);
}
total = missed + covered;
if (total > 0) {
coveragePct = covered * 100.0 / total;
df = new DecimalFormat("0.#");
print("Covered instructions overall: " + covered + "/" + total + " (" + df.format(coveragePct) + "%)");
coverageOk = coveragePct >= minCoverage;
} else {
print("Skipping coverage check: no coverage data found");
}
} catch (FileNotFoundException e) {
print("Skipping coverage check: coverage report file not found (" + jacocoCsv + ")");
} catch (IOException e) {
print("Skipping coverage check: error reading coverage report file");
} finally {
if (input != null) {
input.close();
}
return coverageOk;
}
</condition>
</evaluateBeanshell>
</rules>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment