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.
To create a new rule:
- Login as an administrator
- Go to Configuration > Quality Profile
- Select one of the quality profiles whose language you want to add a new rule
- Look for the XPath rule template:
- Copy this template to create a new rule:
Write your XPath rule (it should comply to XPath 1.0):
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: