Skip to end of metadata
Go to start of metadata

Table of Contents

SonarQube provides a quick and easy way to add new coding rules directly via the web interface for certain languages using XPath expressions. For XML, which is already immediately accessible to XPath, you can simply write your rules and check them using any of the freely available tools for examining XPath on XML. If you're writing rules for XML, skip down to the Adding your rule to the server section once you've got your rules written.

For other languages how to access a variable, for example, in XPath is less obvious, so we've provided tools.

Writing an XPath Rule using SSLR Toolkit

The rules must be written in XPath (version 1.0) to navigate the language's Abstract Syntax Tree (AST). For most languages, an SSLR Toolkit is provided to help you navigate the AST. You need to download the sslr-{language}-toolkit-{version}.jar file corresponding to the version of your language plugin you have on your SonarQube instance.

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. Knowing the XPath language is the only prerequisite, and there are a lot of tutorials on XPath online.

The latest version of SSLR Toolkit can be downloaded from following locations:

For an SSLR preview, consider the following JavaScript source code sample:

HelloWorld.js
function HelloWorld(hour) {
  if (hour) {
    this.hour = hour;
  } else {
    var date = new Date();
    this.hour = date.getHours();
  }
  this.displayGreeting = function() {
    if (this.hour >= 22 || this.hour <= 5)
      document.write("Good night, World!");
    else
      document.write("Hello, World!");
  }  
}

While parsing source code, SonarQube builds an Abstract Syntax Tree (AST) for it, and the SSLR Toolkit provided for each language will show you SonarQube's AST for a given piece of code. Here's the AST for our JavaScript sample:

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.

Adding your Rule to the Server

Once your new rule is written, you can add it SonarQube:

  1. Login as an Quality Profile Administrator
  2. Go to Rules page
  3. Select the Language for which you want to create the XPath rule
  4. Tick the Template criterion and select "Show Templates Only" 
  5. Look for the XPath rule template:
     
  6. Click on it to create a new instance of XPath rule: 
  7. Feed the form:
  8. Paste in the XPath query (it should comply to XPath 1.0) you wrote and tested using the SSLR toolkit:

  9. Once your rule is added to SonarQube, activate it in a Quality Profile and run an analysis.
  • No labels