The SonarQube JSON plugin can be enhanced by writing custom rules through a plugin using SonarQube JSON API. This sample plugin is designed to help you get started writing your own plugin and custom rules.
- Download and install SonarQube 5.6 or greater
- Install the JSON plugin (2.0 or greater) either by a direct download or through the Update Center.
- Install this sample plugin by a direct download
- Start SonarQube
- Activate some of the custom rules implemented in this sample plugin. "Forbidden keys should not be used" for example.
- Install your favorite analyzer (SonarQube Scanner, Maven, Ant, etc.) and analyze your code. Note that Java 8 is required to run an analysis.
- Browse the issues through the web interface
- Create a standard SonarQube plugin from scratch or start from this sample plugin
- Attach this plugin to the SonarQube JSON plugin through the POM:
- Add the dependency to the JSON plugin
- Add the following property to the
sonar-packaging-maven-plugin
configuration:
<basePlugin>JSON</basePlugin>
- Implement the following extension points:
- Declare the
RulesDefinition
implementation as an extension in thePlugin
extension point.
- Create a class to define the implementation of a rule. It should:
- Either extend
SubscriptionVisitorCheck
orDoubleDispatchVisitorCheck
. - Define the rule's attributes: key, name, priority, etc.
- Either extend
- Declare this class in the class implementing
RulesDefinition
There are two different ways to browse the AST:
To explore part of the AST, override a method from DoubleDispactchVisitor
.
For instance, if you want to explore key nodes, override DoubleDispactchVisitor#visitKey
. This method is called each time a key node is encountered in the AST.
Note: When overriding a visit method, you must call the super method in order to allow the visitor to visit the children of the node.
See ForbiddenKeysCheck
for example.
To explore part of the AST, override SubscriptionVisitor#nodesToVisit
by returning the list of Tree#Kind
nodes you want to visit.
For instance, if you want to explore key nodes the method should return a list containing Tree#Kind#KEY
.
See ForbiddenStringCheck
for example.
Precise issue or file issue or line issue can be created by calling the related method in Issues.
Testing is made easy by the JSONCheckVerifier by using assertions in the check class test.
Examples of coding rule implementation and testing can be found in the JSON plugin json-checks
module.