I’m trying to write a plugin which enforces some license header at the beginning of each source file.
I followed this guide and it seems to work as expected in the unit tests (raises an issue on files where it’s missing). After importing the plugin to my SonarQube server, I can successfully see the rule description and I am able to add it to my Quality Profile.
What I’m confused about is where the analysis and issue discovery actually happens. While the rule definition does appear in the web interface, it never raises any issues on files missing that header.
I’m running my analysis through GitLab CI/CD, using the gradle plugin (running ./gradlew sonar). I suspect that I also need to somehow add the plugin on the project side for the issues to be found, but I’m not entirely sure about it, and don’t know how to do so if it is needed.
Regardless, I wanted to get my custom rule working so that I’d know how to set-up custom rules in the future if needed. I added logging as you suggested, and I see that I’m getting to the point which raises my custom issue (“No valid license header found…”).
However, my custom issues still aren’t present in the report (the custom rule is recognized by the server, but it just says “0” issues).
This is how I’m raising the issue:
@Override
public void leaveFile(JavaFileScannerContext context) {
if (logger.isInfoEnabled()) {
logger.info("Checking for license header in '{}'.", context.getInputFile().filename());
}
String content = context.getFileContent();
SyntaxToken firstToken = context.getTree().firstToken();
// If the file isn't empty (firstToken != null) and the pattern doesn't match (missing header), raise issue.
if (firstToken != null && !HEADER_PATTERN.matcher(content).find()) {
reportIssue(firstToken, LICENSE_HEADER_RULE_NAME);
logger.info("No valid license header found, raising issue.");
} else {
logger.info("Valid license header found.");
}
super.leaveFile(context);
}
Ok, turns out the problem was I had a “-” in my plugin key which is apparently invalid (though SonarQube doesn’t alert this, it just removed it which caused some mismatches).
Removing it fixed the problem and my custom issues are now being generated properly.