There are two ways to extend coding rules:
- Adding XPath rules directly through the SonarQube web interface.
- Extending an existing SonarQube plugin. For example Checkstyle and PMD plugins accept definition of custom checks.
Adding New Rules Using XPath Expressions
The rules have to be written in XPath to navigate the Abstract Syntax Tree (AST). For each language, an SSLR Toolkit is provided to navigate the AST. This SSLR Toolkit is a standalone application that displays the AST for a provided piece of code source. So that you quickly get the nodes names and attributes to write your XPath expression from your code sample. The proper SSLR Toolkit can be downloaded from the language plugin page. So, finally, knowing the XPath language is the only prerequisite. A lot of tutorials on XPath can be found online (see http://www.w3schools.com/xpath/ for example).
While parsing the source code, SonarQube builds an Abstract Syntax Tree (AST).
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.
To create a new rule in SonarQube:
- Login as an administrator
- Go to Configuration > 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 this 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 written, activate those rules and run an analysis.
- Issues on those XPath rules are now logged:
Extending SonarQube Plugins
The following languages can be extended with new rules: