There are two ways to extend coding rules:
- Writing custom rules in Java via a SonarQube plugin
- Adding XPath rules directly through the SonarQube web interface
Note that the first way must be preferred when available because the support of XPath will be eventually dropped.
Writing Custom Rules in Java
The following languages can be extended with new rules written in Java: COBOL and Java.
To go further, you can have a look at the following classes implementing coding rules:
- How to define tags
- How to define rule parameters
- Any rules extending BaseTreeVisitor in https://github.com/SonarSource/sonar-java/tree/master/java-checks/src/main/java/org/sonar/java/checks
See how to extend COBOL rules.
Adding New Rules Using XPath Expressions
The rules must be written in XPath to navigate the language's Abstract Syntax Tree (AST). For each language, an SSLR Toolkit is provided to help you navigate the AST. Each language's SSLR Toolkit is a standalone application that displays the AST for a piece of code source that you feed into it, allowing you to read the node names and attributes from your code sample and write your XPath expression. The proper SSLR Toolkit can be downloaded from the language plugin page. So, knowing the XPath language is the only prerequisite, and there are a lot of tutorials on XPath online (see http://www.w3schools.com/xpath/ for example).
The XPath language provides a way to write coding rules by navigating this AST, and the SSLR Toolkit for the language will give you the ability to test your new rules against your sample code.
Once your new rule is written, you can add it SonarQube:
- Login as an Quality profile administrator
- Go to Quality Profile
- Select one of the quality profiles for the language you wish to add the rule to
- Look for the XPath rule template:
- Copy the template to create a new rule:
Paste in the XPath rule (it should comply to XPath 1.0) you wrote and tested using the SSLR toolkit:
Do not use document.write:
Always use curly braces for if/else statements:
- Once your rule is added to SonarQube, activate it in a profile and run an analysis.
- Issues on those XPath rules are now logged: