|Table of Contents|
There are three ways to extend coding rules:
- Adding XPath rules directly in the Sonar web interface.
- Extending an existing Sonar plugin. For example Checkstyle and PMD plugins accept definition of custom checks.
- Embedding and executing a code analyzer. For example the Checkstyle plugin configures and executes the library Checkstyle.
Solution #1: Adding XPath Rules
While parsing the source code, an Abstract Syntax Tree (AST) is built. A SSDK is provided by each language supporting XPath to get a representation of the AST for a given piece of code.
From this AST, you can now write coding rules using the XPath language.
To do so, login as an administrator, go to Configuration > Quality Profile and go to one of the quality profiles of the language you want to add a new rule.
Select the XPath rule:
Click on Copy rule:
- Function must start with an uppercase letter: TODO
- Do not use document.write: TODO
- Always use curly braces for if/else statements: TODO
Activate those rules on one of your quality profiles and run a Sonar analysis.
Violations on those XPath rules are now logged:
Language Plugins Supporting XPath
- Java through PMD
Solution #2: Extending Sonar Plugins
The following languages can be extended with new rules:
- C: see how to extend C rules
- C#: see how to extend FxCop and Gendarme rules
- Cobol: see how to extend Cobol rules
- PHP: see how to extend PHP CodeSniffer and PHPMD rules
Solution #3: Executing a Code Analyzer
A code analyzer plugin executes the following steps:
- Register definitions of coding rules, when the server is started.
- Optionally define some templates of quality profiles, when the server is started.
- Analyze source code and inject results in database
1. Registering coding rules
This step relates to the extension point org.sonar.api.rules.RuleRepository. A RuleRepository defines a set of coding rules. It usually loads data from a XML file:
The XML file is available in the plugin classloader and looks like :
2. Defining quality profiles
This step relates to the extension point org.sonar.api.profiles.ProfileDefinition. Profiles provided by plugins are registered at server startup and can't be edited by users:
3. Analyzing source code
This step relates to the extension point org.sonar.api.batch.Sensor.